在我們開發plsql程序的過程中,有時候難免要訪問一些外部網站的數據。這個時候我們就要用到utl_http包。
使用utl_http包前需要注意的是,當前的用戶下是否有訪問外部網絡的權限。
如下是自己總結的函數,歡迎大家交流學習。
get方式:
1 function http_get(p_url in varchar2) return clob 2 is 3 http_req utl_http.req; 4 http_resp utl_http.resp; 5 l_raw raw(1024); 6 l_r clob; 7 begin 8 begin 9 http_req:=utl_http.begin_request(p_url,'GET'); 10 http_resp := utl_http.get_response(http_req, TRUE); 11 loop 12 utl_http.read_raw(http_resp, l_raw,1024); 13 l_r:=l_r||utl_raw.cast_to_varchar2(l_raw); 14 end loop; 15 utl_http.end_response(http_resp); 16 exception 17 when utl_http.end_of_body then 18 utl_http.end_response(http_resp); 19 end; 20 return l_r; 21 end;
post方式:
1 function http_post( 2 p_url in varchar2, 3 p_data in varchar2 --a=1&b=2... 4 ) return clob 5 is 6 http_req utl_http.req; 7 http_resp utl_http.resp; 8 l_raw raw(1024); 9 l_r clob; 10 begin 11 begin 12 http_req:=utl_http.begin_request(p_url,'POST'); 13 utl_http.set_header(http_req,'Content-Type','application/x-www-form-urlencoded;charset=utf-8'); 14 utl_http.set_header(http_req,'Content-Length',length(p_data)); 15 utl_http.write_text(http_req,p_data); 16 http_resp := utl_http.get_response(http_req, TRUE); 17 loop 18 utl_http.read_raw(http_resp, l_raw,1024); 19 l_r:=l_r||utl_raw.cast_to_varchar2(l_raw); 20 end loop; 21 utl_http.end_response(http_resp); 22 exception 23 when utl_http.end_of_body then 24 utl_http.end_response(http_resp); 25 end; 26 return l_r; 27 end;
The END.