日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

HttpClient的简单使用

發布時間:2024/4/17 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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次),可能會造成服務器重復處理此請求,如果此請求會修改數據庫,就可能造成數據錯亂。所以如果某個請求不允許這種情況出現的話,可以禁用重復發送功能;
CloseableHttpClient httpclient = HttpClients.custom() ? .setRetryHandler(new StandardHttpRequestRetryHandler(0, false)).build();

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的简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。