HttpClient基本介紹
HttpClient官方網(wǎng)站:hc.apache.org
HttpClient中文網(wǎng)站:http://www.httpclient.cn/
中文網(wǎng)站內(nèi)涵h(huán)ttpclent介紹、用法、面試題等
HttpClien4.5中文教程:https://blog.csdn.net/u011179993/article/category/9264255 很感謝作者的翻譯
HttpClien4.5英文教程:http://www.httpclient.cn/httpclient-tutorial.pdf
學(xué)習(xí)的視頻比較老,好多方法都被棄用了,學(xué)習(xí)起來就是一步一個坎,還是慢慢來,研究一個問題網(wǎng)上查資料好久。主要也不是正經(jīng)開發(fā),代碼能力真的是有限。。。加油吧!!
基礎(chǔ)
歷史
HttpClient 是Apache Jakarta Common 下的子項目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協(xié)議的客戶端編程工具包,并且它支持 HTTP 協(xié)議最新的版本和建議。
而今,Commons HttpClient項目現(xiàn)在已經(jīng)壽終正寢,不再開發(fā)和維護(hù)。取而代之的是Apache Httpcomponents項目,它包括HttpClient和HttpCore兩大模塊,能提供更好的性能和更大的靈活性。
使用方法
使用HttpClient發(fā)送請求、接收響應(yīng)很簡單,一般需要如下幾步即可。
創(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í)行方法是否成功,都必須釋放連接
原文鏈接:https://blog.csdn.net/w372426096/article/details/82713315
Http常見請求類型
1、GET請求會向數(shù)據(jù)庫發(fā)索取數(shù)據(jù)的請求,從而來獲取信息,該請求就像數(shù)據(jù)庫的select操作一樣,只是用來查詢一下數(shù)據(jù),不會修改、增加數(shù)據(jù),不會影響資源的內(nèi)容,即該請求不會產(chǎn)生副作用。無論進(jìn)行多少次操作,結(jié)果都是一樣的。
2、與GET不同的是,PUT請求是向服務(wù)器端發(fā)送數(shù)據(jù)的,從而改變信息,該請求就像數(shù)據(jù)庫的update操作一樣,用來修改數(shù)據(jù)的內(nèi)容,但是不會增加數(shù)據(jù)的種類等,也就是說無論進(jìn)行多少次PUT操作,其結(jié)果并沒有不同。
3、POST請求同PUT請求類似,都是向服務(wù)器端發(fā)送數(shù)據(jù)的,但是該請求會改變數(shù)據(jù)的種類等資源,就像數(shù)據(jù)庫的insert操作一樣,會創(chuàng)建新的內(nèi)容。幾乎目前所有的提交操作都是用POST請求的。
4、DELETE請求顧名思義,就是用來刪除某一個資源的,該請求就像數(shù)據(jù)庫的delete操作。
創(chuàng)建MAVEN依賴
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
了解基本用法
// 打開瀏覽器
CloseableHttpClient httpClient=HttpClients.createDefault();
// 聲明get請求
HttpGet httpGet=new HttpGet("http://www.baidu.com");
// 發(fā)送GET請求
CloseableHttpResponse response=httpClient.execute(httpGet);
try {
<......>
}finally {
response.close();
}
構(gòu)建HTTP請求
方法一
HttpGet httpGet=new HttpGet("http://www.baidu.com");
方法一
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.baidu.com")
.setPath("/f")
.setParameter("kw", "國產(chǎn)動畫")
.build();
HttpGet httpGet=new HttpGet(uri);
GET請求
//1.打開瀏覽器
CloseableHttpClient httpClient = HttpClients.createDefault();
//2.聲明get請求
HttpGet httpGet = new HttpGet("http://www.baidu.com/s?wd=java");
//3.發(fā)送請求
CloseableHttpResponse response = httpClient.execute(httpGet);
//4.判斷狀態(tài)碼
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity = response.getEntity();
//使用工具類EntityUtils,從響應(yīng)中取出實體表示的內(nèi)容并轉(zhuǎn)換成字符串
String string = EntityUtils.toString(entity, "utf-8");
System.out.println(string);
}
//5.關(guān)閉資源
response.close();
httpClient.close();
獲取cookie
HttpClientContext content = HttpClientContext.create();
CloseableHttpResponse response=httpClient.execute(httpget,content);
if (response.getStatusLine().getStatusCode()==200){
HttpEntity entity=response.getEntity();
String string= EntityUtils.toString(entity,"utf-8");
// 獲取cookies
CookieStore cookieStore=content.getCookieStore();
List<Cookie> cookieList = cookieStore.getCookies();
for (Cookie cookie:cookieList){
String name=cookie.getName();
String value = cookie.getValue();
System.out.println("cookie name:"+name+";cookie value:"+value);
}
入?yún)в衏ookie
CloseableHttpClient client=HttpClients.createDefault();
HttpClientContext context=HttpClientContext.create();
context.setCookieStore(this.cookieStore);
CloseableHttpResponse response=client.execute(httpGet,context);
將請求到的cookie攜帶訪問get請求
第一步、在resources下創(chuàng)建一個properties文件,文件內(nèi)寫入請求域名和路徑

第二步 、創(chuàng)建JSON文件模擬請求
[
{
"description": "這是一個響應(yīng)帶有cookie的請求",
"request": {
"uri": "/getcookies",
"method": "get"
},
"response": {
"status": "200",
"text": "獲取cookies成功",
"cookies": {
"login": "true"
},
"headers": {
"Content-Type": "text/html;charset=gbk"
}
}
},
{
"description": "這是一個請求帶有cookie的請求",
"request": {
"uri": "/getrequestcookies",
"method": "get",
"cookies": {
"login": "true"
}
},
"response": {
"status": "200",
"text": "傳入獲取cookies成功",
"headers": {
"Content-Type": "text/html;charset=gbk"
}
}
}
]
第三步、創(chuàng)建TESTNG類,完成cookie的獲取與攜帶cookies入?yún)?/p>
private String urL;
private ResourceBundle bundle;
private CookieStore cookieStore;
@BeforeTest
public void beforeTest(){
bundle=ResourceBundle.getBundle("application", Locale.CHINA);
urL=bundle.getString("test.url");
}
@Test
public void getCookiesTest() throws Exception{
CloseableHttpClient httpClient= HttpClients.createDefault();
// 聲明get請求
HttpGet httpget=new HttpGet(this.urL+bundle.getString("test.getCookies.uri"));
// 發(fā)送get請求
HttpClientContext content = HttpClientContext.create();
CloseableHttpResponse response=httpClient.execute(httpget,content);
if (response.getStatusLine().getStatusCode()==200){
HttpEntity entity=response.getEntity();
String string= EntityUtils.toString(entity,"utf-8");
// 獲取cookies
this.cookieStore=content.getCookieStore();
List<Cookie> cookieList = cookieStore.getCookies();
for (Cookie cookie:cookieList){
String name=cookie.getName();
String value = cookie.getValue();
System.out.println("cookie name:"+name+";cookie value:"+value);
}
}
response.close();
httpClient.close();
}
@Test(dependsOnMethods = {"getCookiesTest"})
public void getRequestCookieTest() throws IOException {
HttpGet httpGet=new HttpGet(this.urL+bundle.getString("test.getRequestCookis.uri"));
CloseableHttpClient client=HttpClients.createDefault();
HttpClientContext context=HttpClientContext.create();
context.setCookieStore(this.cookieStore);
CloseableHttpResponse response=client.execute(httpGet,context);
if (response.getStatusLine().getStatusCode()==200) {
HttpEntity entity=response.getEntity();
String str=EntityUtils.toString(entity, "utf-8");
System.out.println(str);
}
response.close();
client.close();
}
第四步 、利用Mock啟動JSON文件
第五步、執(zhí)行如上類,執(zhí)行結(jié)果如下
