Wednesday, April 09, 2008

UTL_HTTP Example


SET SERVEROUTPUT ON size 1000000
DECLARE
l_req UTL_HTTP.req;
l_resp UTL_HTTP.resp;
l_buffer VARCHAR2(32767);
l_body VARCHAR2(32767);
l_fh UTL_FILE.file_type;
BEGIN
--
-- The variable l_body could be a clob and it might be a xml document for some processing
--
l_body := 'Hi How are you';
l_fh := UTL_FILE.fopen('/home/users/smisra', 'rish1.txt','w', 32767);
l_req := utl_http.begin_request('http://www.cnn.com', 'POST', 'HTTP/1.1');

--
-- Set All the header Tags. All these tags may not be necessary.
-- I have added these tags for future reference.
--
UTL_HTTP.set_header(l_req, 'User-Agent' , 'Mozilla/4.0');
UTL_HTTP.set_header(l_req, 'Content-Type' , 'text/xml; charset=utf-8');
UTL_HTTP.set_header(l_req, 'Content-Length', LENGTH(l_body));

--
-- If you set Context-Lenght tag then you have to write text otherwise request will time out.
--
UTL_HTTP.write_text(l_req, l_body);

l_resp := UTL_HTTP.get_response(l_req);
LOOP
--
-- Suppose response is less than 32767, then loop will execute one and get the data.
-- in second iteration, UTL_HTTP.read_text will find end of body exception and exit.
-- This response might be a xml document
--
UTL_HTTP.read_text(l_resp, l_buffer, 32766);
DBMS_OUTPUT.put_line('Buffer Lenght:'|| LENGTH(l_buffer));
UTL_FILE.put_line(l_fh, l_buffer);
--
--
-- The above line will introduce one extra new line character
-- if your hhtp request output in less than 32k, then you are ok and no need to go through the loop
--
END LOOP;
--
-- This call is not needed because LOOP will always raise enf of dody exception and
-- Exception will end the response
--
UTL_HTTP.end_response(l_resp);
EXCEPTION
WHEN UTL_HTTP.end_of_body THEN
DBMS_OUTPUT.put_line(sqlerrm);
UTL_HTTP.end_response(l_resp);
UTL_FILE.fclose(l_fh);
END;
/

1 comment:

  1. what about writing a request body greater than 32k? i tried to loop over write_text with 32k chunks but i have connection errors etc.

    ReplyDelete