概述
HttpClient 是 Apache Jakarta Common 下的子項目,可以用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本。
HttpClientUtils工具類封裝,doGet()、doPost()、doPut()、doDelete()
1、doGet不帶參數示例
// 創建Httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 創建http GET請求
HttpGet httpGet = new HttpGet("https://xiaoyuan.zhaopin.com/api/sou?pageNumber=2");
CloseableHttpResponse response = null;
try
{
// 執行請求
response = httpclient.execute(httpGet);
// 判斷返回狀態是否爲200
if (response.getStatusLine().getStatusCode() == 200)
{
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println("內容長度:" + content.length());
System.out.println(content);// 響應的內容
}
} finally
{
if (response != null)
{
response.close();
}
httpclient.close();
}
2、doGet帶參數示例
// 創建Httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 定義請求的參數
URI uri = new URIBuilder("https://xiaoyuan.zhaopin.com/api/sou").setParameter("pageNumber", "1")
.setParameter("keyWord", "java").build();
System.out.println(uri);
// 創建http GET請求
HttpGet httpGet = new HttpGet(uri);
CloseableHttpResponse response = null;
try
{
// 執行請求
response = httpclient.execute(httpGet);
// 判斷返回狀態是否爲200
if (response.getStatusLine().getStatusCode() == 200)
{
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally
{
if (response != null)
{
response.close();
}
httpclient.close();
}
3、doPost不帶參數示例
// 創建Httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 創建http POST請求
HttpPost httpPost = new HttpPost("http://www.oschina.net/");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36");
CloseableHttpResponse response = null;
try {
// 執行請求
response = httpclient.execute(httpPost);
// 判斷返回狀態是否爲200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
4、doPost帶參數示例
// 創建Httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 添加信息
HttpPost httpPost = new HttpPost("http://39.106.243.121/eto/add");
// 設置2個post參數,一個是scope、一個是q
List<NameValuePair> pairs = new ArrayList<NameValuePair>(0);
pairs.add(new BasicNameValuePair("CityId", "530"));
pairs.add(new BasicNameValuePair("CityName", "北京"));
pairs.add(new BasicNameValuePair("SubCompanyNumber", "CC000773458D90000002000"));
pairs.add(new BasicNameValuePair("CompanyName", "Oracle"));
pairs.add(new BasicNameValuePair("CompanyTypeId", "5"));
pairs.add(new BasicNameValuePair("IndustryName", "軟件"));
pairs.add(new BasicNameValuePair("CompanySize", "10000人以上"));
pairs.add(new BasicNameValuePair("CompanyNumber", "DC000773458"));
// 構造一個form表單式的實體
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs);
// 將請求實體設置到httpPost對象中
httpPost.setEntity(formEntity);
CloseableHttpResponse response = null;
try
{
// 執行請求
response = httpclient.execute(httpPost);
// 判斷返回狀態是否爲200
if (response.getStatusLine().getStatusCode() == 200)
{
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(content);
}
} finally
{
if (response != null)
{
response.close();
}
httpclient.close();
}
5、HttpClientUtils工具類更精細化的封裝
package com.huazai.b2c.aiyou.utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.huazai.b2c.aiyou.repo.HttpResultData;
/**
*
* @author HuaZai
* @contact [email protected]
* <ul>
* @description HttpClient工具類
* </ul>
* @className HttpUtil
* @package com.huazai.b2c.aiyou.utils
* @createdTime 2017年06月17日
*
* @version V1.0.0
*/
public class HttpClientUtils
{
private CloseableHttpClient httpClient;
public HttpClientUtils()
{
httpClient = HttpClients.createDefault();
}
/**
*
* @author HuaZai
* @contact [email protected]
* @title doGet
* <ul>
* @description 帶參數的doGet請求
* </ul>
* @createdTime 2017年06月17日
* @param uri
* @param map
* @return
* @throws Exception
* @return HttpResultData
*
* @version : V1.0.0
*/
public HttpResultData doGet(String uri, Map<String, Object> map)
{
CloseableHttpResponse response = null;
try
{
// 1、創建URIBuilder對象
URIBuilder uriBuilder = new URIBuilder(uri);
encapRequestParams(map, uriBuilder);
// 3、創建 HttpGet對象
HttpGet httpGet = new HttpGet(uriBuilder.build());
// 4、使用httpClient發起請求
response = httpClient.execute(httpGet);
// 5、解析返回結果,封裝返回對象HttpResultData
HttpResultData resultData = this.parseHttpResultData(response);
// 打印日誌輸出
return resultData;
} catch (Exception e)
{
e.printStackTrace();
// 打印日誌輸出
} finally
{
// 6、釋放資源
try
{
if (response != null)
{
response.close();
}
httpClient.close();
} catch (IOException e)
{
// 打印日誌輸出
e.printStackTrace();
}
}
return null;
}
/**
*
* @author HuaZai
* @contact [email protected]
* @title doGet
* <ul>
* @description 不帶參數的doGet請求
* </ul>
* @createdTime 2017年06月17日
* @param uri
* @return
* @throws Exception
* @return HttpResultData
*
* @version : V1.0.0
*/
public HttpResultData doGet(String uri) throws Exception
{
return this.doGet(uri, null);
}
/**
*
* @author HuaZai
* @contact [email protected]
* @title doPost
* <ul>
* @description 帶參數的doPost請求
* </ul>
* @createdTime 2017年06月17日
* @param uri
* @param map
* @return
* @return HttpResultData
*
* @version : V1.0.0
* @throws Exception
*/
public HttpResultData doPost(String uri, Map<String, Object> map)
{
CloseableHttpResponse response = null;
try
{
// 1、聲明 HttpPost對象
HttpPost request = new HttpPost();
// 2、封裝請求參數,請求數據表單
UrlEncodedFormEntity entity = this.encapRequestParams(map);
// 3、設置請求數據表單
request.setEntity(entity);
// 4、通過HttpClient執行請求
response = httpClient.execute(request);
// 5、解析返回結果,封裝返回對象HttpResultData
HttpResultData resultData = this.parseHttpResultData(response);
// 打印日誌輸出
return resultData;
} catch (Exception e)
{
// 打印日誌輸出
e.printStackTrace();
} finally
{
// 6、釋放資源
try
{
if (response != null)
{
response.close();
}
httpClient.close();
} catch (IOException e)
{
// 打印日誌輸出
e.printStackTrace();
}
}
return null;
}
/**
*
* @author HuaZai
* @contact [email protected]
* @title doPost
* <ul>
* @description 不帶參數的doPost請求
* </ul>
* @createdTime 2017年06月17日
* @param uri
* @return
* @return HttpResultData
*
* @version : V1.0.0
* @throws Exception
*/
public HttpResultData doPost(String uri) throws Exception
{
return this.doPost(uri, null);
}
/**
*
* @author HuaZai
* @contact [email protected]
* @title doPut
* <ul>
* @description 帶參數的doPut請求
* </ul>
* @createdTime 2017年06月17日
* @param uri
* @param map
* @return
* @return HttpResultData
*
* @version : V1.0.0
* @throws Exception
*/
public HttpResultData doPut(String uri, Map<String, Object> map)
{
CloseableHttpResponse response = null;
try
{
// 1、生命HttpPut對象
HttpPut request = new HttpPut();
// 2、封裝請求參數
UrlEncodedFormEntity entity = this.encapRequestParams(map);
// 3、設置請求表單數據
request.setEntity(entity);
// 4、通過HttpClient執行請求
response = httpClient.execute(request);
// 5、封裝解析返回結果,封裝返回對象HttpResultData
HttpResultData resultData = this.parseHttpResultData(response);
// 打印日誌輸出
return resultData;
} catch (Exception e)
{
// 打印日誌輸出
e.printStackTrace();
} finally
{
// 6、釋放資源
try
{
if (response != null)
{
response.close();
}
httpClient.close();
} catch (IOException e)
{
// 打印日誌輸出
e.printStackTrace();
}
}
return null;
}
/**
*
* @author HuaZai
* @contact [email protected]
* @title doPut
* <ul>
* @description 不帶參數的doPut請求
* </ul>
* @createdTime 2017年06月17日
* @param uri
* @return
* @return HttpResultData
*
* @version : V1.0.0
* @throws Exception
*/
public HttpResultData doPut(String uri) throws Exception
{
return this.doPut(uri, null);
}
/**
*
* @author HuaZai
* @contact [email protected]
* @title doDelete
* <ul>
* @description 帶參數的doDelete請求
* </ul>
* @createdTime 2017年06月17日
* @param uri
* @param map
* @return
* @return HttpResultData
*
* @version : V1.0.0
* @throws Exception
*/
public HttpResultData doDelete(String uri, Map<String, Object> map)
{
CloseableHttpResponse response = null;
try
{
// 1、創建URIBuilder對象
URIBuilder uriBuilder = new URIBuilder(uri);
// 2、設置請求參數
this.encapRequestParams(map, uriBuilder);
// 3、創建 HttpGet對象
HttpDelete request = new HttpDelete(uriBuilder.build());
// 4、使用httpClient發起請求
response = httpClient.execute(request);
// 5、解析返回結果,封裝返回對象HttpResultData
HttpResultData resultData = this.parseHttpResultData(response);
// 打印日誌輸出
return resultData;
} catch (Exception e)
{
// 打印日誌輸出
e.printStackTrace();
} finally
{
// 6、釋放資源
try
{
if (response != null)
{
response.close();
}
httpClient.close();
} catch (IOException e)
{
// 打印日誌輸出
e.printStackTrace();
}
}
return null;
}
/**
*
* @author HuaZai
* @contact [email protected]
* @title doDelete
* <ul>
* @description 不帶參數的doDelete請求
* </ul>
* @createdTime 2017年06月17日
* @param uri
* @return
* @return HttpResultData
*
* @version : V1.0.0
* @throws Exception
*/
public HttpResultData doDelete(String uri) throws Exception
{
return this.doDelete(uri, null);
}
/**
*
* @author HuaZai
* @contact [email protected]
* @title parseHttpResultData
* <ul>
* @description 解析返回結果,封裝返回對象HttpResultData
* </ul>
* @createdTime 2017年06月17日
* @param response
* @return
* @throws IOException
* @return HttpResultData
*
* @version : V1.0.0
*/
private HttpResultData parseHttpResultData(CloseableHttpResponse response) throws IOException
{
// 響應狀態碼
int code = response.getStatusLine().getStatusCode();
String body = null;
// 響應消息體
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null)
{
body = EntityUtils.toString(httpEntity, "UTF-8");
}
// 封裝返回實體
HttpResultData resultData = new HttpResultData(code, body);
return resultData;
}
/**
*
* @author HuaZai
* @contact [email protected]
* @title encapRequestParams
* <ul>
* @description 封裝請求參數,請求數據表單
* </ul>
* @createdTime 2017年06月17日
* @param map
* @return
* @throws Exception
* @return UrlEncodedFormEntity
*
* @version : V1.0.0
*/
private UrlEncodedFormEntity encapRequestParams(Map<String, Object> map) throws Exception
{
// 是否是帶參數的請求
if (map != null)
{
// 聲明表單容器
List<NameValuePair> parameters = new ArrayList<>();
for (Map.Entry<String, Object> entry : map.entrySet())
{
// 封裝容器
BasicNameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
parameters.add(nameValuePair);
}
// 創建表單實體
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
return entity;
}
return null;
}
/**
*
* @author HuaZai
* @contact [email protected]
* @title encapRequestParams
* <ul>
* @description 設置請求參數
* </ul>
* @createdTime 2017年06月17日
* @param map
* @param uriBuilder
* @return void
*
* @version : V1.0.0
*/
private void encapRequestParams(Map<String, Object> map, URIBuilder uriBuilder)
{
// 是否是帶參數的請求
if (map != null)
{
for (Map.Entry<String, Object> entry : map.entrySet())
{
// 封裝請求參數
uriBuilder.addParameter(entry.getKey(), entry.getValue().toString());
}
}
}
}
好了,關於 HttpClientUtils工具類封裝,doGet()、doPost()、doPut()、doDelete() 就寫到這兒了,如果還有什麼疑問或遇到什麼問題歡迎掃碼提問,也可以給我留言哦,我會一一詳細的解答的。
歇後語:“ 共同學習,共同進步 ”,也希望大家多多關注CSND的IT社區。
作 者: | 華 仔 |
聯繫作者: | [email protected] |
來 源: | CSDN (Chinese Software Developer Network) |
原 文: | https://blog.csdn.net/Hello_World_QWP/article/details/102912797 |
版權聲明: | 本文爲博主原創文章,請在轉載時務必註明博文出處! |