使用java進行http通訊

Http通訊概述

Http通訊主要有兩種方式POST方式和GET方式。前者經過Http消息實體發送數據給服務器,安全性高,數據傳輸大小沒有限制,後者經過URL的查詢字符串傳遞給服務器參數,以明文顯示在瀏覽器地址欄,保密性差,最多傳輸2048個字符。可是GET請求並非一無可取——GET請求大多用於查詢(讀取資源),效率高。POST請求用於註冊、登陸等安全性較高且向數據庫中寫入數據的操做。html

除了POST和GET,http通訊還有其餘方式!請參見http請求的方法java

編碼前的準備

在進行編碼以前,咱們先建立一個Servlet,該Servlet接收客戶端的參數(name和age),並響應客戶端。數據庫

java@WebServlet(urlPatterns={"/demo.do"})
public class DemoServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        PrintWriter pw = response.getWriter();
        pw.print("您使用GET方式請求該Servlet。<br />" + "name = " + name + ",age = " + age);
        pw.flush();
        pw.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        PrintWriter pw = response.getWriter();
        pw.print("您使用POST方式請求該Servlet。<br />" + "name = " + name + ",age = " + age);
        pw.flush();
        pw.close();
    }

}

使用JDK實現http通訊

使用URLConnection實現GET請求

  1. 實例化一個java.net.URL對象;
  2. 經過URL對象的openConnection()方法獲得一個java.net.URLConnection;
  3. 經過URLConnection對象的getInputStream()方法得到輸入流;
  4. 讀取輸入流;
  5. 關閉資源。
javapublic void get() throws Exception{

    URL url = new URL("http://127.0.0.1/http/demo.do?name=Jack&age=10");
    URLConnection urlConnection = url.openConnection();                                                    // 打開鏈接
    BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"utf-8")); // 獲取輸入流
    String line = null;
    StringBuilder sb = new StringBuilder();
    while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
    }

    System.out.println(sb.toString());
}

運行結果1

使用HttpURLConnection實現POST請求

java.net.HttpURLConnectionjava.net.URL的子類,提供了更多的關於http的操做(getXXX 和 setXXX方法)。該類中定義了一系列的HTTP狀態碼:apache

http狀態碼

javapublic void post() throws IOException{

    URL url = new URL("http://127.0.0.1/http/demo.do");
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

    httpURLConnection.setDoInput(true);
    httpURLConnection.setDoOutput(true);        // 設置該鏈接是能夠輸出的
    httpURLConnection.setRequestMethod("POST"); // 設置請求方式
    httpURLConnection.setRequestProperty("charset", "utf-8");

    PrintWriter pw = new PrintWriter(new BufferedOutputStream(httpURLConnection.getOutputStream()));
    pw.write("name=welcome");                   // 向鏈接中輸出數據(至關於發送數據給服務器)
    pw.write("&age=14");
    pw.flush();
    pw.close();

    BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));
    String line = null;
    StringBuilder sb = new StringBuilder();
    while ((line = br.readLine()) != null) {    // 讀取數據
        sb.append(line + "\n");
    }

    System.out.println(sb.toString());
}

運行結果2

使用httpclient進行http通訊

httpclient大大簡化了JDK中http通訊的實現。瀏覽器

maven依賴:安全

xml<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.3.6</version>
</dependency>

GET請求

javapublic void httpclientGet() throws Exception{

    // 建立HttpClient對象
    HttpClient client = HttpClients.createDefault();

    // 建立GET請求(在構造器中傳入URL字符串便可)
    HttpGet get = new HttpGet("http://127.0.0.1/http/demo.do?name=admin&age=40");

    // 調用HttpClient對象的execute方法得到響應
    HttpResponse response = client.execute(get);

    // 調用HttpResponse對象的getEntity方法獲得響應實體
    HttpEntity httpEntity = response.getEntity();

    // 使用EntityUtils工具類獲得響應的字符串表示
    String result = EntityUtils.toString(httpEntity,"utf-8");
    System.out.println(result);
}

運行結果3

POST請求

javapublic void httpclientPost() throws Exception{

    // 建立HttpClient對象
    HttpClient client = HttpClients.createDefault();

    // 建立POST請求
    HttpPost post = new HttpPost("http://127.0.0.1/http/demo.do");

    // 建立一個List容器,用於存放基本鍵值對(基本鍵值對即:參數名-參數值)
    List<BasicNameValuePair> parameters = new ArrayList<>();
    parameters.add(new BasicNameValuePair("name", "張三"));
    parameters.add(new BasicNameValuePair("age", "25"));

    // 向POST請求中添加消息實體
    post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));

    // 獲得響應並轉化成字符串
    HttpResponse response = client.execute(post);
    HttpEntity httpEntity = response.getEntity();
    String result = EntityUtils.toString(httpEntity,"utf-8");
    System.out.println(result);
}

運行結果4

參考文檔

httpclient官網服務器

相關文章
相關標籤/搜索