(一)簡介
HttpClient是Apache的一個開源庫,相比於JDK自帶的URLConnection等,使用起來更靈活方便。
使用方法可以大致分為如下八步曲:
1、創建一個HttpClient對象;
2、創建一個Http請求對象並設置請求的URL,比如GET請求就創建一個HttpGet對象,POST請求就創建一個HttpPost對象;
3、如果需要可以設置請求對象的請求頭參數,也可以往請求對象中添加請求參數;
4、調用HttpClient對象的execute方法執行請求;
5、獲取請求響應對象和響應Entity;
6、從響應對象中獲取響應狀態,從響應Entity中獲取響應內容;
7、關閉響應對象;
8、關閉HttpClient.
(二)在本地創建一個Servlet程序
在本地創建一個Servlet程序並跑在Tomcat服務器中,主要用於下一步測試HttpClient發送請求。
注:Servlet的創建方法詳見:微信公眾號開發【技術基礎】(一):Eclipse+Tomcat搭建本地服務器並跑通HelloWorld程序
1、Servlet類:
1 import java.io.PrintWriter; 2 3 import javax.servlet.http.HttpServlet; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6 7 public class HelloWorld extends HttpServlet { 8 private static final long serialVersionUID = 4601029764222607869L; 9 10 @Override 11 protected void doGet(HttpServletRequest req, HttpServletResponse resp) { 12 // 1. 設置編碼格式 13 resp.setContentType("text/html"); 14 resp.setCharacterEncoding("UTF-8"); 15 16 // 2. 往返回體中寫返回數據 17 PrintWriter writer = null; 18 try { 19 writer = resp.getWriter(); 20 writer.print("Hello world! 你好,世界!!"); 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } finally { 24 writer.close(); 25 } 26 } 27 28 @Override 29 protected void doPost(HttpServletRequest req, HttpServletResponse resp) { 30 // 1. 獲取請求的參數 31 String userName = req.getParameter("username"); 32 String password = req.getParameter("password"); 33 34 // 2. 往返回體寫返回數據 35 PrintWriter writer = null; 36 try { 37 writer = resp.getWriter(); 38 writer.print("your username is:" + userName + "\nyour password is:" + password); 39 } catch (Exception e) { 40 e.printStackTrace(); 41 } finally { 42 writer.close(); 43 } 44 } 45 46 }
2、web.xml(新加內容):
1 <servlet> 2 <servlet-name>helloWorld</servlet-name> 3 <servlet-class>com.servlet.HelloWorld</servlet-class> 4 </servlet> 5 6 <servlet-mapping> 7 <servlet-name>helloWorld</servlet-name> 8 <url-pattern>/hello</url-pattern> 9 </servlet-mapping>
(三)測試HttpClient發送GET和POST請求
1、HttpClient測試類:
1 package com.test.method; 2 3 import java.io.IOException; 4 import java.io.UnsupportedEncodingException; 5 import java.util.ArrayList; 6 import java.util.List; 7 8 import org.apache.http.HttpEntity; 9 import org.apache.http.NameValuePair; 10 import org.apache.http.ParseException; 11 import org.apache.http.client.ClientProtocolException; 12 import org.apache.http.client.entity.UrlEncodedFormEntity; 13 import org.apache.http.client.methods.CloseableHttpResponse; 14 import org.apache.http.client.methods.HttpGet; 15 import org.apache.http.client.methods.HttpPost; 16 import org.apache.http.impl.client.CloseableHttpClient; 17 import org.apache.http.impl.client.HttpClients; 18 import org.apache.http.message.BasicNameValuePair; 19 import org.apache.http.util.EntityUtils; 20 21 /** 22 * 測試HttpClient發送各種請求的方法 23 * 24 * @author Administrator 25 * 26 */ 27 public class HttpClientTest { 28 // 發送請求的url 29 public static final String REQUEST_URL = "http://localhost:8080/TomcatTest/hello"; 30 31 /** 32 * 測試發送GET請求 33 */ 34 public void get() { 35 // 1. 創建一個默認的client實例 36 CloseableHttpClient client = HttpClients.createDefault(); 37 38 try { 39 // 2. 創建一個httpget對象 40 HttpGet httpGet = new HttpGet(REQUEST_URL); 41 System.out.println("executing GET request " + httpGet.getURI()); 42 43 // 3. 執行GET請求並獲取響應對象 44 CloseableHttpResponse resp = client.execute(httpGet); 45 46 try { 47 // 4. 獲取響應體 48 HttpEntity entity = resp.getEntity(); 49 System.out.println("------"); 50 51 // 5. 打印響應狀態 52 System.out.println(resp.getStatusLine()); 53 54 // 6. 打印響應長度和響應內容 55 if (null != entity) { 56 System.out.println("Response content length = " + entity.getContentLength()); 57 System.out.println("Response content is:\n" + EntityUtils.toString(entity)); 58 } 59 60 System.out.println("------"); 61 } finally { 62 // 7. 無論請求成功與否都要關閉resp 63 resp.close(); 64 } 65 } catch (ClientProtocolException e) { 66 e.printStackTrace(); 67 } catch (ParseException e) { 68 e.printStackTrace(); 69 } catch (IOException e) { 70 e.printStackTrace(); 71 } finally { 72 // 8. 最終要關閉連接,釋放資源 73 try { 74 client.close(); 75 } catch (Exception e) { 76 e.printStackTrace(); 77 } 78 } 79 } 80 81 /** 82 * 測試發送POST請求 83 */ 84 public void post() { 85 // 1. 獲取默認的client實例 86 CloseableHttpClient client = HttpClients.createDefault(); 87 // 2. 創建httppost實例 88 HttpPost httpPost = new HttpPost(REQUEST_URL); 89 // 3. 創建參數隊列(鍵值對列表) 90 List<NameValuePair> paramPairs = new ArrayList<NameValuePair>(); 91 paramPairs.add(new BasicNameValuePair("username", "admin")); 92 paramPairs.add(new BasicNameValuePair("password", "123456")); 93 94 UrlEncodedFormEntity entity; 95 96 try { 97 // 4. 將參數設置到entity對象中 98 entity = new UrlEncodedFormEntity(paramPairs, "UTF-8"); 99 100 // 5. 將entity對象設置到httppost對象中 101 httpPost.setEntity(entity); 102 103 System.out.println("executing POST request " + httpPost.getURI()); 104 105 // 6. 發送請求並回去響應 106 CloseableHttpResponse resp = client.execute(httpPost); 107 108 try { 109 // 7. 獲取響應entity 110 HttpEntity respEntity = resp.getEntity(); 111 112 // 8. 打印出響應內容 113 if (null != respEntity) { 114 System.out.println("------"); 115 System.out.println(resp.getStatusLine()); 116 System.out.println("Response content is : \n" + EntityUtils.toString(respEntity, "UTF-8")); 117 118 System.out.println("------"); 119 } 120 } finally { 121 // 9. 關閉響應對象 122 resp.close(); 123 } 124 125 } catch (ClientProtocolException e) { 126 e.printStackTrace(); 127 } catch (UnsupportedEncodingException e) { 128 e.printStackTrace(); 129 } catch (IOException e) { 130 e.printStackTrace(); 131 } finally { 132 // 10. 關閉連接,釋放資源 133 try { 134 client.close(); 135 } catch (Exception e) { 136 e.printStackTrace(); 137 } 138 } 139 } 140 141 public static void main(String[] args) { 142 HttpClientTest test = new HttpClientTest(); 143 // 測試GET請求 144 test.get(); 145 // 測試POST請求 146 test.post(); 147 } 148 }
2、輸出結果:
executing GET request http://localhost:8080/TomcatTest/hello
------
HTTP/1.1 200 OK
Response content length = 34
Response content is:
Hello world! 你好,世界!!
------
executing POST request http://localhost:8080/TomcatTest/hello
------
HTTP/1.1 200 OK
Response content is :
your username is:admin
your password is:123456
------
(四)jar包下載
所需jar包打包下載地址:https://pan.baidu.com/s/1mhJ9iT6