1. 程式人生 > >webservice學習筆記(十三):HttpUrlConnection請求Web Service

webservice學習筆記(十三):HttpUrlConnection請求Web Service

1.大致流程:

a.前端觸發事件

b.ajax傳遞到servlet

c.servlet獲取請求值並寫成請求包的形式傳遞給服務端

d.響應碼為200的時候,讀取資料並且寫到瀏覽器上

e.jquery對報文進行解析,獲取return標籤中的響應值並輸出

2.首先新建一個Servlet,程式碼如下:

package com.wayne.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class wayneServlet
 * 跨域,使用HttpUrlConnection傳送webservice請求
 * 該servlet為客戶端
 */


@WebServlet("/wayneServlet")
public class wayneServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public wayneServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name=request.getParameter("name");
        System.out.println("doPost");
      
 //請求報文,拼接name等引數
        String data="<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:q0='http://ws.wayne.com/' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><soapenv:Body><q0:sayHello><arg0>"+name+"</arg0></q0:sayHello></soapenv:Body></soapenv:Envelope>";;
      
 //宣告Url物件,引數為服務端的地址
        URL url=new URL("http://localhost:8080/day_six_ws_cxf_spring_web_ajax/gotham/gotham");
      
 //原本應該是UrlConnection物件,因為遵循http協議所以要宣告為HttpUrlConnection物件
        HttpURLConnection connection=(HttpURLConnection) url.openConnection();
      
 //請求方式
        connection.setRequestMethod("POST");
      
 //是否可以輸出資料
        connection.setDoOutput(true);
      
 //是否可以接收伺服器端的資料
        connection.setDoInput(true);
        
//設定資料格式
        connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
      
 //寫資料
        OutputStream os = connection.getOutputStream();
        os.write(data.getBytes("utf-8"));
        
//獲取響應碼
        int responseCode = connection.getResponseCode();
        if(responseCode==200){
          
 //讀資料,xml格式的字串
            InputStream is = connection.getInputStream();
          
 //獲取讀到的位元組數
            System.out.println("return"+is.available());
            
//設定響應格式
            response.setContentType("text/text;charset=utf-8");
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buffer=new byte[1024];
            int len=0;
            if((len=is.read(buffer))>0){
              
 //寫到瀏覽器
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
        }
    }

}
 

3.在jsp頁面建立按鈕,並編寫jquery觸發事件,片段程式碼如下:

 

4.執行結果如下: