使用JAVA實現http通訊詳解_java

來源:互聯網
上載者:User

Http通訊概述

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

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

編碼前的準備

在進行編碼之前,我們先建立一個Servlet,該Servlet接收用戶端的參數(name和age),並響應用戶端。

@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請求

執行個體化一個java.net.URL對象;
通過URL對象的openConnection()方法得到一個java.net.URLConnection;
通過URLConnection對象的getInputStream()方法獲得輸入資料流;
讀取輸入資料流;
關閉資源。

public 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());}

使用HttpURLConnection實現POST請求

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

 

public 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());}

使用httpclient進行http通訊

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

maven依賴:

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

GET請求

public 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);}

POST請求

public 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);}

HttpClient是Apache Jakarta Common下的子項目,用來提供高效的、最新的、功能豐富的支援HTTP協議的用戶端編程工具包,並且它支援HTTP協議最新的版本和建議。HttpClient已經應用在很多的項目中,比如Apache Jakarta上很著名的另外兩個開源項目Cactus和HTMLUnit都使用了HttpClient。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.