Http通信概述
Http通信主要有兩種方式POST方式和GET方式。前者通過(guò)Http消息實(shí)體發(fā)送數(shù)據(jù)給服務(wù)器,安全性高,數(shù)據(jù)傳輸大小沒有限制,后者通過(guò)URL的查詢字符串傳遞給服務(wù)器參數(shù),以明文顯示在瀏覽器地址欄,保密性差,最多傳輸2048個(gè)字符。但是GET請(qǐng)求并不是一無(wú)是處——GET請(qǐng)求大多用于查詢(讀取資源),效率高。POST請(qǐng)求用于注冊(cè)、登錄等安全性較高且向數(shù)據(jù)庫(kù)中寫入數(shù)據(jù)的操作。
除了POST和GET,http通信還有其他方式!請(qǐng)參見http請(qǐng)求的方法
編碼前的準(zhǔn)備
在進(jìn)行編碼之前,我們先創(chuàng)建一個(gè)Servlet,該Servlet接收客戶端的參數(shù)(name和age),并響應(yīng)客戶端。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
@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方式請(qǐng)求該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方式請(qǐng)求該Servlet。<br />" + "name = " + name + ",age = " + age); pw.flush(); pw.close(); } } |
使用JDK實(shí)現(xiàn)http通信
使用URLConnection實(shí)現(xiàn)GET請(qǐng)求
實(shí)例化一個(gè)java.net.URL對(duì)象;
通過(guò)URL對(duì)象的openConnection()方法得到一個(gè)java.net.URLConnection;
通過(guò)URLConnection對(duì)象的getInputStream()方法獲得輸入流;
讀取輸入流;
關(guān)閉資源。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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實(shí)現(xiàn)POST請(qǐng)求
java.net.HttpURLConnection是java.net.URL的子類,提供了更多的關(guān)于http的操作(getXXX 和 setXXX方法)。該類中定義了一系列的HTTP狀態(tài)碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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 ); // 設(shè)置該連接是可以輸出的 httpURLConnection.setRequestMethod( "POST" ); // 設(shè)置請(qǐng)求方式 httpURLConnection.setRequestProperty( "charset" , "utf-8" ); PrintWriter pw = new PrintWriter( new BufferedOutputStream(httpURLConnection.getOutputStream())); pw.write( "name=welcome" ); // 向連接中輸出數(shù)據(jù)(相當(dāng)于發(fā)送數(shù)據(jù)給服務(wù)器) 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 ) { // 讀取數(shù)據(jù) sb.append(line + "\n" ); } System.out.println(sb.toString()); } |
使用httpclient進(jìn)行http通信
httpclient大大簡(jiǎn)化了JDK中http通信的實(shí)現(xiàn)。
maven依賴:
1
2
3
4
5
|
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version> 4.3 . 6 </version> </dependency> |
GET請(qǐng)求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public void httpclientGet() throws Exception{ // 創(chuàng)建HttpClient對(duì)象 HttpClient client = HttpClients.createDefault(); // 創(chuàng)建GET請(qǐng)求(在構(gòu)造器中傳入U(xiǎn)RL字符串即可) HttpGet get = new HttpGet( "http://127.0.0.1/http/demo.do?name=admin&age=40" ); // 調(diào)用HttpClient對(duì)象的execute方法獲得響應(yīng) HttpResponse response = client.execute(get); // 調(diào)用HttpResponse對(duì)象的getEntity方法得到響應(yīng)實(shí)體 HttpEntity httpEntity = response.getEntity(); // 使用EntityUtils工具類得到響應(yīng)的字符串表示 String result = EntityUtils.toString(httpEntity, "utf-8" ); System.out.println(result); } |
POST請(qǐng)求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public void httpclientPost() throws Exception{ // 創(chuàng)建HttpClient對(duì)象 HttpClient client = HttpClients.createDefault(); // 創(chuàng)建POST請(qǐng)求 HttpPost post = new HttpPost( "http://127.0.0.1/http/demo.do" ); // 創(chuàng)建一個(gè)List容器,用于存放基本鍵值對(duì)(基本鍵值對(duì)即:參數(shù)名-參數(shù)值) List<BasicNameValuePair> parameters = new ArrayList<>(); parameters.add( new BasicNameValuePair( "name" , "張三" )); parameters.add( new BasicNameValuePair( "age" , "25" )); // 向POST請(qǐng)求中添加消息實(shí)體 post.setEntity( new UrlEncodedFormEntity(parameters, "utf-8" )); // 得到響應(yīng)并轉(zhuǎn)化成字符串 HttpResponse response = client.execute(post); HttpEntity httpEntity = response.getEntity(); String result = EntityUtils.toString(httpEntity, "utf-8" ); System.out.println(result); } |
HttpClient是Apache Jakarta Common下的子項(xiàng)目,用來(lái)提供高效的、最新的、功能豐富的支持HTTP協(xié)議的客戶端編程工具包,并且它支持HTTP協(xié)議最新的版本和建議。HttpClient已經(jīng)應(yīng)用在很多的項(xiàng)目中,比如Apache Jakarta上很著名的另外兩個(gè)開源項(xiàng)目Cactus和HTMLUnit都使用了HttpClient。