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 ()方法取得輸入流;
讀取輸入流;
關閉資源。
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 和 XXXset方法)。在該類別中定義了一系列的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); }
HttpClient是Apache Jakarta Common下的子項目,用來提供高效的、最新的、功能豐富的支援HTTP協定的客戶端程式設計工具包,並且它支援HTTP協定最新的版本和建議。 HttpClient已經應用在很多的專案中,像是Apache Jakarta上很著名的另外兩個開源專案Cactus和HTMLUnit都使用了HttpClient。
更多使用JAVA實現http通信詳解相關文章請關注PHP中文網!