Oracle 通过UTL_HTTP 发送http请求并处理发送内容中包含空格和特殊字符的问题

来源:互联网 发布:pmp含金量 知乎 编辑:程序博客网 时间:2024/05/22 12:20
    Oracle中可以通过UTL_HTTP发送http请求,例子如下:
CREATE OR REPLACE PROCEDURE test(v_userid in varchar2,v_content in varchar2 ) IS  req  UTL_HTTP.REQ;  resp UTL_HTTP.RESP;  v_message  varchar2(10000);  xmlstr  varchar2(30000);begin    begin      req  := UTL_HTTP.BEGIN_REQUEST('http://ip:port/weixin?userid='||v_userid||'&'||'content='||v_content);      utl_http.set_header(req, 'Content-Type', 'text/html; charset=utf-8');      utl_http.write_text(req,xmlstr); --通过body发送消息      xmlstr:=v_content;       utl_http.set_header(req, 'Content-Length',lengthb(xmlstr));      utl_http.write_text(req,xmlstr);      resp := UTL_HTTP.GET_RESPONSE(req);        LOOP        UTL_HTTP.read_line(resp,v_message, TRUE);        dbms_output.put_line(v_message);      END LOOP;      utl_http.end_request(req);      utl_http.end_response(resp);    EXCEPTION      WHEN utl_http.end_of_body THEN        utl_http.end_response(resp);        WHEN OTHERS THEN      utl_http.end_response(resp);      utl_http.end_request(req);    end;END test;
    调用的时候,如果v_content中包含空格或者其他特殊字符的时候请求就会失败,要想解决这个问题的话,就需要对内容进行编码,我们可以通过url encode来对相应的内容编码,web应用接收到相应的数据做相应的解码即可,修改后的代码如下:
CREATE OR REPLACE PROCEDURE test(v_userid in varchar2,v_content in varchar2 ) IS  req  UTL_HTTP.REQ;  resp UTL_HTTP.RESP;  v_message  varchar2(10000);  xmlstr  varchar2(30000);begin    begin      req  := UTL_HTTP.BEGIN_REQUEST('http://ip:port/weixin?userid='||v_userid||'&'||'content='||utl_url.escape(v_content,true,'UTF8'));      utl_http.set_header(req, 'Content-Type', 'text/html; charset=utf-8');      utl_http.write_text(req,xmlstr); --通过body发送消息      xmlstr:=utl_url.escape(v_content,true,'UTF8');       utl_http.set_header(req, 'Content-Length',lengthb(xmlstr));      utl_http.write_text(req,xmlstr);      resp := UTL_HTTP.GET_RESPONSE(req);        LOOP        UTL_HTTP.read_line(resp,v_message, TRUE);        dbms_output.put_line(v_message);      END LOOP;      utl_http.end_request(req);      utl_http.end_response(resp);    EXCEPTION      WHEN utl_http.end_of_body THEN        utl_http.end_response(resp);        WHEN OTHERS THEN      utl_http.end_response(resp);      utl_http.end_request(req);    end;END test;
阅读全文
0 0