HttpClient的简单使用
目錄
- HttpClient的使用
- 一、maven坐標
- 二、 主要API
- 2.1 CloseableHttpClient
- 2.2 HttpClients
- 2.3 URIBuilder
- 2.4 HttpGet
- 2.5 HttpPost
- 2.6 HttpEntity
- 2.7 StringEntity
- 2.8 NameValuePair
- 2.9 UrlEncodedFormEntity
- 2.10 InputStreamEntity
- 2.11 CloseableHttpResponse
- 2.12 HttpEntity
- 2.13 EntityUtils
- 三、 案例代碼
- 3.1 發送不帶請求參數的get請求
- 3.2 發送攜帶請求參數的get請求
- 3.3 發送不帶請求參數以及其他請求體數據的post請求
- 3.4 發送攜帶表單格式請求參數的post請求
- 3.5 發送攜帶一般字符串請求體數據的post請求
- 3.6 發送 https的get請求
- 四、 一個簡單的HttpClientUtil
HttpClient的使用
一、maven坐標
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version> </dependency>二、 主要API
2.1 CloseableHttpClient
表示Http客戶端對象,用來發送請求并得到響應。線程安全,如果項目中只是偶爾httpclinet,建議每次使用時都新建、關閉此對象。如果項目中頻繁使用httpclinet,建議把此對象作為單例使用;
httpClient.execute(request); // 執行get、post等請求
httpClient.close(); // 關閉此客戶端對象,釋放資源
2.2 HttpClients
用來創建HttpClinet對象的工具類
createDefault(); /創建默認的CloseableHttpClient對象
2.3 URIBuilder
用來構建URI,可以方便的在請求路徑后面追加查詢字符串
URI uri = new URIBuilder("http://localhost:8080/test")// 設置請求路徑.setCharset(Charset.forName("UTF-8"))// 設置編碼(默認為項目編碼),一般不用設置.addParameter("k1", "v1")// 連續調用此方法可以設置多個請求參數.build();// 構建并返回URI對象URI表示一個資源路徑,可以認為等價于URL
2.4 HttpGet
表示一個get請求對象
HttpGet httpGet = new HttpGet(uri); httpGet.addHeader("h1", "v1");2.5 HttpPost
表示一個post請求對象
HttpPost httpPost = new HttpPost("http://localhost:8080/test/test2"); httpPost.addHeader("h1", "v1");2.6 HttpEntity
表示一個請求體
2.7 StringEntity
表示字符串請求體
StringEntity entity = new StringEntity("hello httpclient !", "UTF-8");2.8 NameValuePair
表示一對鍵值對數據
NameValuePair param = new BasicNameValuePair("age", "16");2.9 UrlEncodedFormEntity
表示進行URL編碼的、符合表單提交格式的字符串請求體
List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", "蛋蛋")); params.add(new BasicNameValuePair("age", "16")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); httpPost.setEntity(entity);2.10 InputStreamEntity
表示字節流形式的請求體
InputStreamEntity entity = new InputStreamEntity(instream);2.11 CloseableHttpResponse
表示一個響應對象
CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.headerIterator();//響應頭迭代器 HttpEntity resultEntity = httpResponse.getEntity();//響應體數據2.12 HttpEntity
表示一個響應體(和請求體是同一個類)
HttpEntity resultEntity = httpResponse.getEntity(); // 使用流的方式操作響應體數據 InputStream inputStream = resultEntity.getContent(); // 如果響應體是字符串數據,可能需要字符編碼信息 Header header = resultEntity.getContentEncoding();2.13 EntityUtils
可以方便取出響應體數據的工具類,因為此工具類會把所有響應體數據全部緩存到內存中,所以如果響應體數據量較大的話建議直接使用httpEntity.getContent()獲取到響應體的讀取流,進行流操作;
HttpEntity resultEntity = httpResponse.getEntity(); //此方法會自動根據響應頭中的編碼信息對響應體內容進行編碼,也可以手動指定編碼 String result = EntityUtils.toString(resultEntity);三、 案例代碼
注意:
httpclinet可自動管理cookie,所以支持session會話
- 如果發送請求或者接收響應過程中出現的IOException,httpclinet默認會重新發送請求(嘗試5次),可能會造成服務器重復處理此請求,如果此請求會修改數據庫,就可能造成數據錯亂。所以如果某個請求不允許這種情況出現的話,可以禁用重復發送功能;
3.1 發送不帶請求參數的get請求
CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try {httpClient = HttpClients.createDefault();HttpGet httpGet = new HttpGet("http://localhost:8080/test");httpResponse httpResponse = httpClient.execute(httpGet);HttpEntity entity = httpResponse.getEntity();String result = EntityUtils.toString(entity);// 處理result的代碼... } finally {if (httpResponse != null) {httpResponse.close();}if (httpClient != null) {httpClient.close();} }3.2 發送攜帶請求參數的get請求
CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try {httpClient = HttpClients.createDefault();URI uri = new URIBuilder("http://localhost:8080/test")// 設置請求路徑.setCharset(Charset.forName("UTF-8"))// 設置編碼(默認為項目編碼),一般不用設置.addParameter("k1", "v1")// 連續調用此方法可以設置多個請求參數.build();// 構建并返回URI對象HttpGet httpGet = new HttpGet(uri);httpResponse = httpClient.execute(httpGet);HttpEntity entity = httpResponse.getEntity();String result = EntityUtils.toString(entity);// 處理result的代碼... } finally {if (httpResponse != null) {httpResponse.close();}if (httpClient != null) {httpClient.close();} }3.3 發送不帶請求參數以及其他請求體數據的post請求
CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try {httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost("http://localhost:8080/test");httpResponse = httpClient.execute(httpPost);HttpEntity entity = httpResponse.getEntity();String result = EntityUtils.toString(entity);// 處理result的代碼... } finally {if (httpResponse != null) {httpResponse.close();}if (httpClient != null) {httpClient.close();} }3.4 發送攜帶表單格式請求參數的post請求
CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try {httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost("http://localhost:8080/test");List<NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("name", "Hali"));params.add(new BasicNameValuePair("age", "16"));UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");httpPost.setEntity(entity);httpResponse = httpClient.execute(httpPost);HttpEntity resultEntity = httpResponse.getEntity();String result = EntityUtils.toString(resultEntity);// 處理result的代碼... } finally {if (httpResponse != null) {httpResponse.close();}if (httpClient != null) {httpClient.close();} }3.5 發送攜帶一般字符串請求體數據的post請求
CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; try {httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost("http://localhost:8080/test");StringEntity entity = new StringEntity("hello httpclient !", "UTF-8");httpPost.setEntity(entity);httpResponse = httpClient.execute(httpPost);HttpEntity resultEntity = httpResponse.getEntity();String result = EntityUtils.toString(resultEntity);// 處理result的代碼... } finally {if (httpResponse != null) {httpResponse.close();}if (httpClient != null) {httpClient.close();} }3.6 發送 https的get請求
/*** 創建一個可以訪問Https類型URL的工具類,返回一個CloseableHttpClient實例*/ public static CloseableHttpClient createSSLClientDefault(){try {SSLContext sslContext=new SSLContextBuilder().loadTrustMaterial(null,new TrustStrategy() {//信任所有public boolean isTrusted(X509Certificate[] chain, String authType)throws CertificateException {return true;}}).build();SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(sslContext);return HttpClients.custom().setSSLSocketFactory(sslsf).build();} catch (KeyManagementException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (KeyStoreException e) {e.printStackTrace();}return HttpClients.createDefault(); } /*** @throws IOException * @throws ClientProtocolException * */ public static void main(String[] args) throws ClientProtocolException, IOException {//從工具方法中獲得對應的可以訪問Https的httpClientCloseableHttpClient httpClient =createSSLClientDefault(); HttpGet httpGet=new HttpGet("https://etrade.ccbfund.cn/etrading/tradereq/main.do?method=doInit&isHome=1&menuId=10000");//自己先在瀏覽器登錄一下,自行復制具體的CookiehttpGet.setHeader("Cookie", "HS_ETS_SID=4jSFY2wWwT0gPrWJ45ly!-1286216704; Null=31111111.51237.0000; logtype=2; certtype=0; certNo=33****************; isorgloginpage_cookie=0; hs_etrading_customskin=app_css");//設置代理,方便Fiddle捕獲具體信息RequestConfig config=RequestConfig.custom().setProxy(HttpHost.create("127.0.0.1:8888")).build();httpGet.setConfig(config);//執行get請求,獲得對應的響應實例CloseableHttpResponse response=httpClient.execute(httpGet);//打印響應的到的html正文HttpEntity entity =response.getEntity();String html=EntityUtils.toString(entity);System.out.println(html);//關閉連接response.close();httpClient.close(); }四、 一個簡單的HttpClientUtil
地址: https://github.com/lunarku/Code_Snippets/blob/master/CodeSnippets/jdk/src/main/java/jdk/util/http/HttpClientUtils.java
轉載于:https://www.cnblogs.com/jxkun/p/9399102.html
總結
以上是生活随笔為你收集整理的HttpClient的简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript中的坐标
- 下一篇: web框架应具备的功能