utl_tcp 实现tcp连接
function :
create or replace function socket1(ip in varchar2,port in varchar2,request_clob in clob) return clob is response_clob clob; con utl_tcp.connection; ret_val pls_integer; offset integer; cloblen integer; clobPart VARCHAR2(4096); tmpclob clob; FUNCTION next_row(clob_in IN CLOB, off_in IN INTEGER) RETURN VARCHAR2 IS BEGIN RETURN dbms_lob.substr(clob_in, 1024, off_in); END next_row; Begin dbms_output.put_line(‘create tcp connection ...‘); con := utl_tcp.open_connection(remote_host => ip, remote_port => port , charset => ‘UTF-8‘); cloblen := LENGTH(request_clob); offset := 1; LOOP EXIT WHEN offset >= clobLen; clobPart := next_row(request_clob, offset); ret_val := utl_tcp.WRITE_line(con, clobPart); offset := offset + 1024; END LOOP; ret_val := utl_tcp.write_line(con); ----must added,mark the request end dbms_output.put_line(‘send tcp request‘); response_clob := empty_clob(); LOOP tmpclob := empty_clob(); tmpclob := to_clob(utl_tcp.GET_text (con,1024)); ---get response response_clob := response_clob||tmpclob; exit when LENGTH(tmpclob) = 0; end LOOP; dbms_output.put_line(‘get tcp response‘); utl_tcp.close_connection(con); return response_clob; Exception when others then if sqlcode = ‘-29259‘ then dbms_output.put_line(‘SOCKET ERROR -> Message: ‘||sqlerrm); dbms_output.put_line(‘SOCKET ERROR -> Position: ‘||DBMS_UTILITY.FORMAT_ERROR_BACKTRACE); utl_tcp.close_connection(con); return response_clob; else dbms_output.put_line(‘SOCKET ERROR -> Message: ‘||sqlerrm); dbms_output.put_line(‘SOCKET ERROR -> Position: ‘||DBMS_UTILITY.FORMAT_ERROR_BACKTRACE); utl_tcp.close_connection(con); return null; end if; END; /
test script:
set define off; set serveroutput on; declare l_ip varchar2(32767); l_port varchar2(32767); l_address varchar2(32767); ret_val pls_integer; response clob; con utl_tcp.connection; begin l_address := ‘www.baidu.com‘; l_ip := UTL_INADDR.GET_HOST_ADDRESS(l_address); dbms_output.put_line(‘ip of baidu is: ‘||l_ip); l_port := ‘80‘; response := socket1(l_ip,l_port,to_clob(‘GET / HTTP/1.0‘)); printxml(response); end; /
xml output procedure:
CREATE OR REPLACE PROCEDURE PrintXML (i_respxml IN CLOB) is line VARCHAR2 (32767); v_clob CLOB; v_length NUMBER; v_amount NUMBER; v_newline NUMBER; v_offset NUMBER := 1; BEGIN IF i_respXML IS NULL THEN RETURN; ELSE v_clob := i_respxml; v_length := DBMS_LOB.getlength (v_clob); WHILE v_offset <= v_length LOOP v_newline := INSTR(v_clob, chr(10), v_offset); if v_newline = 0 then v_amount := v_length - v_offset + 1; else v_amount := v_newline - v_offset; end if; if v_amount > 32767 then v_amount := 32766; end if; if v_amount = 0 then v_amount := 1; end if; DBMS_LOB.READ (v_clob, v_amount, v_offset, line); dbms_output.put_line(‘| ‘|| line); v_offset := v_offset + v_amount + 1; END LOOP; DBMS_LOB.freetemporary (v_clob); END IF; END PrintXML; / show errors;
时间: 2024-11-05 11:55:58