1.需要的maven依賴:
<!--httpClient需要的依賴-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!--//httpclient緩存-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.5</version>
</dependency>
<!--//http的mime類型都在這裏面-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.2</version>
</dependency>
2.發送get請求
//使用httpClient發送get請求
public void sentGetMethod(){
//1.先創建httpClient對象,使用默認的方式即可
CloseableHttpClient httpClient= HttpClients.createDefault();
//2.設置url並且創建某種請求方式實例
//比如:(在百度上搜索helloworld出現的路徑)url:https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0
// &rsv_idx=1&tn=baidu&wd=helloworld&rsv_pq=c6735cf70000fe15
// &rsv_t=7e25dm7uzHpmOwrFNF33FXbom45Px0Bs0F8PP3Bcm8RMOysmKlfA%2FuqKoU4&rqlang=cn
// &rsv_enter=1&rsv_sug3=9&rsv_sug1=5&rsv_sug7=101
//url的構建也可以使用字符串拼接的方式
try {
URI url=new URIBuilder()
.setScheme("https")//設置協議
.setHost("www.baidu.com")
.setPath("/s")
.setParameter("ie","utf-8")
.setParameter("rsv_idx","1")
.setParameter("tn","baidu")
.setParameter("wd","helloworld")
.setParameter("rsv_pq","c6735cf70000fe15")
.setParameter("rsv_t","7e25dm7uzHpmOwrFNF33FXbom45Px0Bs0F8PP3Bcm8RMOysmKlfA%2FuqKoU4")
.setParameter("rqlang","cn")
.setParameter("rsv_enter","1")
.setParameter("rsv_sug3","9")
.setParameter("rsv_sug1","5")
.setParameter("rsv_sug7","101")
.build();
System.out.println(url);
HttpGet httpGet=new HttpGet(url);
InputStream inputStream=null;
CloseableHttpResponse httpResponse=null;
try {
//3.執行httpClient
httpResponse=httpClient.execute(httpGet);
//可以輸出請求的結果
System.out.println(httpResponse.getStatusLine().getStatusCode());
//4.獲取相應的結果
//4.1使用EntityUtils.toString()方式 --不推薦
//2種方式只能2選一存在,會互相沖突
HttpEntity entity=httpResponse.getEntity(); //獲取響應的實體
// if (entity!=null){
// System.out.println(EntityUtils.toString(entity,"utf-8"));
// }else {
// //如果entity爲空,那麼直接消化掉即可
// EntityUtils.consume(entity);
// }
System.out.println("------------------------我是美麗的分割線--------------------");
//4.2使用InputStream方式 --推建
inputStream=entity.getContent();
//轉換成字符流
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line="";
while ((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//關閉InputStream和response
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpResponse!=null){
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
;
}
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
3.httpClient發送post請求(攜帶json數據)
//發送post請求 攜帶json數據的
public void sendPostMethod(String url){
//1.創建httpClient
CloseableHttpClient httpClient=HttpClients.createDefault();
//2.創建post請求方式實例
HttpPost httpPost=new HttpPost(url);
//2.1設置請求頭 發送的是json數據格式
httpPost.setHeader("Content-type", "application/json;charset=utf-8");
httpPost.setHeader("Connection", "Close");
//3.設置參數---設置消息實體 也就是攜帶的數據
/*
* 比如傳遞:
* {
"username": "aries",
"password": "666666"
}
*/
String jsonStr=" {\"username\":\"aries\",\"password\":\"666666\"}";
StringEntity entity = new StringEntity(jsonStr.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8"); //設置編碼格式
// 發送Json格式的數據請求
entity.setContentType("application/json");
//把請求消息實體塞進去
httpPost.setEntity(entity);
//4.執行http的post請求
CloseableHttpResponse httpResponse=null;
InputStream inputStream=null;
try {
httpResponse=httpClient.execute(httpPost);
//5.對返回的數據進行處理
//5.1判斷是否成功
System.out.println(httpResponse.getStatusLine().getStatusCode());
//5.2對數據進行處理
HttpEntity httpEntity=httpResponse.getEntity();
inputStream=httpEntity.getContent(); //獲取content實體內容
//封裝成字符流來輸出
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line="";
while ((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//6.關閉inputStream和httpResponse
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpResponse!=null){
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4.httpClient發送post請求/攜帶x-www-form-urlencoded數據格式
//發送post請求 攜帶非json數據
public void sendPostMethod1(String url) throws Exception {
// 1、創建一個httpClient客戶端對象
CloseableHttpClient httpClient=HttpClients.createDefault();
// 2、創建一個HttpPost請求
HttpPost httpPost = new HttpPost(url);
//設置請求頭
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); //設置傳輸的數據格式
//攜帶普通的參數params的方式
List<NameValuePair> params=new ArrayList<>();
params.add(new BasicNameValuePair("username", "kylin"));
params.add(new BasicNameValuePair("password", "123456"));
String str=EntityUtils.toString(new UrlEncodedFormEntity(params,Consts.UTF_8));
//這裏就是:username=kylin&password=123456
System.out.println(str);
//放參數進post請求裏面 從名字可以知道 這個類是專門處理x-www-form-urlencoded 添加參數的
httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
// 7、執行post請求操作,並拿到結果
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
// 獲取結果實體
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
//進行輸出操作 這裏就簡單的使用EntityUtils工具類的toString()方法
System.out.println(EntityUtils.toString(entity,"UTF-8"));
}
else EntityUtils.consume(entity);
//最後釋放資源之類的
}
總結:
1.創建httpClient對象創建默認的對象就夠使用了
2.創建某種請求方法的實例
例如有:get方式---- HttpGet
post方式-----HttpPost
put方式------HttpPut
delete方式 ------HttpDelete
3.如果有參數的話就設置參數
get請求:
方式1:使用URI類的方法來創建
方式2:直接使用字符串拼接那種
post請求:
使用setEntity()方式來攜帶不同的數據類型(需要設置)
4.發送請求
執行httpClient.execute() --返回CloseableHttpResponse對象
5.獲取請求的結果
獲取HttpEntity的實體之後,對http文檔的查看
方式一:EntityUtils.toString(entity,"utf-8") 不推薦
方式二:使用InputStream類
6.關閉連接釋放資源
先關閉inputStream
再關閉response