詳解HttpClient用法
上篇文章給大家介紹了HttpClient詳細(xì)使用示例詳解,喜歡的朋友可以點擊查看,今天繼續(xù)給大家介紹HttpClient用法,具體內(nèi)容如下所示;
1.簡介
HttpClient是Apache Jakarta Common下的子項目,用來提供高效的、最新的、功能豐富的支持HTTP協(xié)議的客戶端編程工具包,并且它支持HTTP協(xié)議最新的版本和建議。HttpClient已經(jīng)應(yīng)用在很多的項目中,比如Apache Jakarta上很著名的另外兩個開源項目Cactus和HTMLUnit都使用了HttpClient。
HttpClient相比傳統(tǒng)JDK自帶的URLConnection,增加了易用性和靈活性,它不僅使客戶端發(fā)送Http請求變得容易,而且也方便開發(fā)人員測試接口(基于Http協(xié)議的),提高了開發(fā)的效率,也方便提高代碼的健壯性。
2.特性
- 基于標(biāo)準(zhǔn)、純凈的java語言。實現(xiàn)了Http1.0和Http1.1
- 以可擴展的面向?qū)ο蟮慕Y(jié)構(gòu)實現(xiàn)了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。
- 支持HTTPS協(xié)議。
- 通過Http代理建立透明的連接。
- 利用CONNECT方法通過Http代理建立隧道的https連接。
- Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos認(rèn)證方案。
- 插件式的自定義認(rèn)證方案。
- 便攜可靠的套接字工廠使它更容易的使用第三方解決方案。
- 連接管理器支持多線程應(yīng)用。支持設(shè)置最大連接數(shù),同時支持設(shè)置每個主機的最大連接數(shù),發(fā)現(xiàn)并關(guān)閉過期的連接。
- 自動處理Set-Cookie中的Cookie。
- 插件式的自定義Cookie策略。
- Request的輸出流可以避免流中內(nèi)容直接緩沖到socket服務(wù)器。
- Response的輸入流可以有效的從socket服務(wù)器直接讀取相應(yīng)內(nèi)容。
- 在http1.0和http1.1中利用KeepAlive保持持久連接。
- 直接獲取服務(wù)器發(fā)送的response code和 headers。
- 設(shè)置連接超時的能力。
- 實驗性的支持http1.1 response caching。
- 源代碼基于Apache License 可免費獲取。
3.使用方法
- 創(chuàng)建HttpClient對象。
- 創(chuàng)建請求方法的實例,并指定請求URL。如果需要發(fā)送GET請求,創(chuàng)建HttpGet對象;如果需要發(fā)送POST請求,創(chuàng)建HttpPost對象。
- 如果需要發(fā)送請求參數(shù),可調(diào)用HttpGet、HttpPost共同的setParams(HttpParams params)方法來添加請求參數(shù);對于HttpPost對象而言,也可調(diào)用setEntity(HttpEntity entity)方法來設(shè)置請求參數(shù)。
- 調(diào)用HttpClient對象的execute(HttpUriRequest request)發(fā)送請求,該方法返回一個HttpResponse。
- 調(diào)用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可獲取服務(wù)器的響應(yīng)頭;調(diào)用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務(wù)器的響應(yīng)內(nèi)容。程序可通過該對象獲取服務(wù)器的響應(yīng)內(nèi)容。
- 釋放連接。無論執(zhí)行方法是否成功,都必須釋放連接
4、實例
4.1 導(dǎo)入pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wo</groupId>
<artifactId>HttpClient_test</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
</dependencies>
</project>
4.2.get請求方式
@RequestMapping("findAll")
public String findAll() throws Exception{
//獲得Http客戶端
CloseableHttpClient build = HttpClientBuilder.create().build();
//創(chuàng)建get請求
HttpGet httpGet = new HttpGet("http://localhost:8088/lunbo/findAll");
//執(zhí)行請求
CloseableHttpResponse execute = build.execute(httpGet);
//解析返回值
StatusLine statusLine = execute.getStatusLine();
//獲取到返回狀態(tài)碼
System.out.println("狀態(tài)碼為:"+statusLine.getStatusCode());
String s = EntityUtils.toString(execute.getEntity());
build.close();
execute.close();
return s;
}
4.3 post請求方式
//post路徑傳參
@RequestMapping("/findAllPost/{page}/{size}")
public String findAll(@PathVariable("page") int page,@PathVariable("size") int size) throws Exception {
//獲得Http客戶端
CloseableHttpClient build = HttpClientBuilder.create().build();
//創(chuàng)建post請求
HttpPost httpPost = new HttpPost("http://localhost:8088/position/findAll/"+page+"/"+size);
//執(zhí)行請求
CloseableHttpResponse execute = build.execute(httpPost);
//解析返回值
StatusLine statusLine = execute.getStatusLine();
//獲取到返回狀態(tài)碼
System.out.println("狀態(tài)碼為:"+statusLine.getStatusCode());
String s = EntityUtils.toString(execute.getEntity());
build.close();
execute.close();
return s;
}
//post map傳參
@RequestMapping("findById")
public String findById(@RequestParam("id") Integer id)throws Exception{
//創(chuàng)建httpclicent請求對象
CloseableHttpClient build = HttpClientBuilder.create().build();
//聲明請求方式
HttpPost httpPost = new HttpPost("http://localhost:8088/position/findById");
//聲明攜帶參數(shù)
Map map=new HashMap<>();
map.put("id",id);
//將map轉(zhuǎn)換為json格式
Object o = JSONObject.toJSON(map);
//設(shè)置請求 參數(shù)的編碼格式
StringEntity stringEntity = new StringEntity(o.toString(), "utf-8");
//將參數(shù)設(shè)置到請求對象中
httpPost.setEntity(stringEntity);
//設(shè)置content-Type
httpPost.setHeader("Content-Type","application/json");
//執(zhí)行請求
CloseableHttpResponse execute = build.execute(httpPost);
//解析返回值
StatusLine statusLine = execute.getStatusLine();
//獲取到返回狀態(tài)碼
System.out.println("狀態(tài)碼為:"+statusLine.getStatusCode());
String s = EntityUtils.toString(execute.getEntity());
build.close();
execute.close();
return s;
}
到此這篇關(guān)于詳解HttpClient用法的文章就介紹到這了,更多相關(guān)HttpClient用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Hadoop+HBase+ZooKeeper分布式集群環(huán)境搭建步驟
這篇文章主要介紹了Hadoop+HBase+ZooKeeper分布式集群環(huán)境搭建,集群環(huán)境至少需要3個節(jié)點,1個Master,2個Slave,節(jié)點之間局域網(wǎng)連接,可以相互ping通,本文通過實例給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04
Java并發(fā)LinkedBlockingQueue源碼分析
這篇文章主要為大家介紹了Java并發(fā)LinkedBlockingQueue源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
java并發(fā)數(shù)據(jù)包Exchanger線程間的數(shù)據(jù)交換器
這篇文章主要為大家介紹了java并發(fā)數(shù)據(jù)包使用數(shù)據(jù)交換器Exchanger來進(jìn)行線程之間的數(shù)據(jù)交換。有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-03-03
Java中的StringTokenizer實現(xiàn)字符串切割詳解
這篇文章主要介紹了Java中的StringTokenizer實現(xiàn)字符串切割詳解,java.util工具包提供了字符串切割的工具類StringTokenizer,Spring等常見框架的字符串工具類(如Spring的StringUtils),需要的朋友可以參考下2024-01-01

