欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Oracle發送http請求

程序员文章站 2024-01-22 21:23:04
...

一、Oracle存儲過程
1、调用发送方法的存储过程

CREATE OR REPLACE procedure test_CallHttpRequest(
   pi_URL  in varchar2,    --發送的Http URL
   po_ReMsg  out varchar2  --返回信息
) is

  obj_xmldoc sys.xmltype;       --響應報文xml對象
  ro_xmlContent varchar2(10000); --請求報文
          
begin
  --要發送的報文
  ro_xmlContent:='<?xml version="1.0" encoding="GBK"?>
  <TXLife>
  <TXLifeRequest>
  <TransRefGUID>0066667626</TransRefGUID>
    <TransType tc="WLSCBS_BL_BK_0002">測試</TransType>
    <TransExeDate>2018-12-03</TransExeDate>
    <TransExeTime>10:12:30</TransExeTime>
    <Billcard>
      <CardType tc="166">單證類型</CardType>
      <BackType tc="14">單證回銷類型值</BackType>
    </Billcard>
  </TXLifeRequest>
</TXLife>';
  
  --調用發送方法
  test_SqlHttpRequest(pi_URL, ro_xmlContent, po_ReMsg, obj_xmldoc);

end test_CallHttpRequest;

2、具体的发送存储过程

CREATE OR REPLACE procedure test_SqlHttpRequest(
  pi_URL  in varchar2,    --發送的Http URL
  pi_Content in varchar2, --發送的報文?容
  po_ReMsg out varchar2,  --錯誤?容
  po_xmltype out xmltype  --響應報文?容
)
as
  obj_http_req   UTL_HTTP.REQ;    --http請求對象
  obj_http_resp  UTL_HTTP.RESP;   --http響應對象
  v_req_clob     varchar2(32767); --請求報文
  v_resp_clob     clob;           --響應報文
  v_buffer_text  varchar2(32767); --緩存
  TIMEOUT          INTEGER   DEFAULT 3600;
  
begin
  
  v_req_clob:=pi_Content;
  
  -- 初始化晌應CLOB.
  DBMS_LOB.createtemporary(v_resp_clob, FALSE);

  -- 初始化HTTP請求參數.
  UTL_HTTP.SET_TRANSFER_TIMEOUT(TIMEOUT);
  obj_http_req  := UTL_HTTP.BEGIN_REQUEST (pi_URL, 'POST');
  UTL_HTTP.SET_HEADER (obj_http_req,'Content-Type','text/xml;chartset=utf-8');
  v_req_clob:=utl_url.escape(v_req_clob,true,'UTF-8');--進行url編碼
  UTL_HTTP.SET_HEADER (obj_http_req,'Content-Length',lengthb(v_req_clob));
  UTL_HTTP.SET_BODY_CHARSET(obj_http_req,'UTF-8');
  --發送HTTP請求
  UTL_HTTP.WRITE_TEXT (obj_http_req,v_req_clob);
  --接收響應
  obj_http_resp := UTL_HTTP.GET_RESPONSE(obj_http_req);

  BEGIN
    LOOP
      UTL_HTTP.READ_TEXT(obj_http_resp, v_buffer_text, 32767);
      DBMS_LOB.WRITEAPPEND(v_resp_clob, length(v_buffer_text), v_buffer_text);
    END LOOP;
    --關閉HTTP連接
    UTL_HTTP.END_RESPONSE(obj_http_resp);
  EXCEPTION
      WHEN UTL_HTTP.REQUEST_FAILED THEN
          UTL_HTTP.END_RESPONSE(obj_http_resp);
          DBMS_LOB.freetemporary(v_resp_clob);
          po_ReMsg := 'HTTP請求失敗:' || 'DBS' || to_char(SQLCODE) || ':' || substr(SQLERRM,1,128);
      WHEN UTL_HTTP.TRANSFER_TIMEOUT THEN
          UTL_HTTP.END_RESPONSE(obj_http_resp);
          DBMS_LOB.freetemporary(v_resp_clob);
          po_ReMsg := 'HTTP請求超時失敗:' || 'DBS' || to_char(SQLCODE) || ':' || substr(SQLERRM,1,128);
      WHEN UTL_HTTP.END_OF_BODY THEN
          UTL_HTTP.END_RESPONSE(obj_http_resp);
      WHEN OTHERS THEN
          UTL_HTTP.END_RESPONSE(obj_http_resp);
          DBMS_LOB.freetemporary(v_resp_clob);
          po_ReMsg := 'HTTP請求錯誤:' || 'DBS' || to_char(SQLCODE) || ':' || substr(SQLERRM,1,128);
  END;
  
    v_resp_clob := utl_url.unescape(v_resp_clob, 'utf-8');--進行url解碼
    dbms_output.put_line('返回-------------->'||v_resp_clob); 
    --創建XMLTYPE對象
    po_xmltype:=sys.XMLTYPE(v_resp_clob);
    --釋放clob
    DBMS_LOB.freetemporary(v_resp_clob);
    po_ReMsg := '請求成功!';
    
   EXCEPTION
    WHEN OTHERS THEN
        UTL_HTTP.END_RESPONSE(obj_http_resp);
        DBMS_LOB.freetemporary(v_resp_clob);
        po_ReMsg := 'XML?容錯誤:' || 'DBS' || to_char(SQLCODE) || ':' || substr(SQLERRM,1,128);
        
end test_SqlHttpRequest;

Oracle發送http請求
Oracle發送http請求
二、Java部分
Oracle發送http請求

package servlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * Servlet implementation class OracleHttpResponse
 */
@WebServlet("/OracleHttpResponse")
public class OracleHttpResponse extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OracleHttpResponse() {
        super();
        // TODO Auto-generated constructor stub
        System.out.println("constructor");
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		System.out.println("doPost方法");
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("doGet方法");
		// 设置接收的内容编码
        request.setCharacterEncoding("utf-8");
        // 接收请求的输入流数据
        String sendMessage = null;

        try {
            InputStream in = request.getInputStream();

            InputStreamReader isr = new InputStreamReader(in,"UTF-8");
            BufferedReader br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }

            sendMessage = buffer.toString();

        } catch (InterruptedIOException e) {
            e.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (NullPointerException npe) {
            npe.printStackTrace();
        }
        sendMessage = java.net.URLDecoder.decode(sendMessage,"utf-8");
        System.out.println("oracle过来的xml数据:" + sendMessage);

        OutputStream url_out = null;
        String xmlData = CreateResponseData();
        
        response.setContentType("text/xml;charset=utf-8");
        xmlData = java.net.URLEncoder.encode(xmlData,"utf-8").replaceAll("\\+",  "%20");
        response.reset();
        url_out = response.getOutputStream();
        url_out.write(xmlData.getBytes("utf-8"), 0, xmlData.getBytes("utf-8").length);
        url_out.flush();
        url_out.close();
	}
	
	private String CreateResponseData() {
        Document document = DocumentHelper.createDocument();
        // 增加根节点
        Element TXLife = document.addElement("TXLife");

        Element TXLifeResponse = TXLife.addElement("TXLifeResponse");
        Element TransRefGUID = TXLifeResponse.addElement("TransRefGUID");
        TransRefGUID.setText("1000000000");

        Element TransType = TXLifeResponse.addElement("TransType");
        TransType.setText("测试同步交易");
        TransType.addAttribute("tc", "WLSCBS_QY_BL_0001");

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = dateFormat.format(new Date());

        Element TransExeDate = TXLifeResponse.addElement("TransExeDate");
        TransExeDate.setText(dateStr.split(" ")[0]);

        Element TransExeTime = TXLifeResponse.addElement("TransExeTime");
        TransExeTime.setText(dateStr.split(" ")[1]);

        Element TransResult = TXLifeResponse.addElement("TransResult");
        Element ResultCode = TransResult.addElement("ResultCode");
        ResultCode.setText("测试成功");
        ResultCode.addAttribute("tc", "1");
        return document.asXML();
    }
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}
	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub

		System.out.println("init");
	}
}

三、測試
Oracle發送http請求
java輸出
Oracle發送http請求
Oracle發送http請求
本文链接:https://blog.csdn.net/shangshaohui2009/article/details/88556722