在我们开发plsql程序的过程中,有时候难免要访问一些外部网站的数据。这个时候我们就要用到utl_http包。

使用utl_http包前需要注意的是,当前的用户下是否有访问外部网络的权限。

如下是自己总结的函数,欢迎大家交流学习。

get方式:

 function http_get(p_url in varchar2) return clob
is
http_req utl_http.req;
http_resp utl_http.resp;
l_raw raw(1024);
l_r clob;
begin
begin
http_req:=utl_http.begin_request(p_url,'GET');
http_resp := utl_http.get_response(http_req, TRUE);
loop
utl_http.read_raw(http_resp, l_raw,1024);
l_r:=l_r||utl_raw.cast_to_varchar2(l_raw);
end loop;
utl_http.end_response(http_resp);
exception
when utl_http.end_of_body then
utl_http.end_response(http_resp);
end;
return l_r;
end;

post方式:

 function  http_post(
p_url in varchar2,
p_data in varchar2 --a=1&b=2...
) return clob
is
http_req utl_http.req;
http_resp utl_http.resp;
l_raw raw(1024);
l_r clob;
begin
begin
http_req:=utl_http.begin_request(p_url,'POST');
utl_http.set_header(http_req,'Content-Type','application/x-www-form-urlencoded;charset=utf-8');
utl_http.set_header(http_req,'Content-Length',length(p_data));
utl_http.write_text(http_req,p_data);
http_resp := utl_http.get_response(http_req, TRUE);
loop
utl_http.read_raw(http_resp, l_raw,1024);
l_r:=l_r||utl_raw.cast_to_varchar2(l_raw);
end loop;
utl_http.end_response(http_resp);
exception
when utl_http.end_of_body then
utl_http.end_response(http_resp);
end;
return l_r;
end;

The END.

05-11 15:12