import java.io.Serializable;
/**
* @Description: <p> HttpClientResult </p>
* @Author: - Jason
* @CreatTime:2019/7/24 - 17:57
* @Modify By:
* @ModifyTime: 2019/7/24
* @Modify marker:
*/
public class HttpClientResult implements Serializable {
/**
* 響應(yīng)狀態(tài)碼
*/
private int code;
/**
* 響應(yīng)數(shù)據(jù)
*/
private String content;
public HttpClientResult(int code) {
this.code = code;
}
public HttpClientResult(int code, String content) {
this.code = code;
this.content = content;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.HttpEntityEnclosingRequestBase;
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.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
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 java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @Description: <p> HttpClientUtils </p>
* @Author: - Jason
* @CreatTime:2019/7/24 - 17:42
* @Modify By:
* @ModifyTime: 2019/7/24
* @Modify marker:
*/
public class HttpClientUtils {
/**
* 編碼格式。發(fā)送編碼格式統(tǒng)一用UTF-8
*/
private static final String ENCODING = "UTF-8";
/**
* 設(shè)置連接超時(shí)時(shí)間走触,單位毫秒。
*/
private static final int CONNECT_TIMEOUT = 6000;
/**
* 請(qǐng)求獲取數(shù)據(jù)的超時(shí)時(shí)間(即響應(yīng)時(shí)間)形导,單位毫秒。
*/
private static final int SOCKET_TIMEOUT = 6000;
/**
* 發(fā)送get請(qǐng)求榛了;不帶請(qǐng)求頭和請(qǐng)求參數(shù)
* @param url 請(qǐng)求地址
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url) throws Exception {
return doGet(url, null, null);
}
/**
* 發(fā)送get請(qǐng)求凡桥;帶請(qǐng)求參數(shù)
* @param url 請(qǐng)求地址
* @param params 請(qǐng)求參數(shù)集合
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
return doGet(url, null, params);
}
/**
* 發(fā)送get請(qǐng)求;帶請(qǐng)求頭和請(qǐng)求參數(shù)
* @param url 請(qǐng)求地址
* @param headers 請(qǐng)求頭集合
* @param params 請(qǐng)求參數(shù)集合
* @return
* @throws Exception
*/
public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 創(chuàng)建httpClient對(duì)象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 創(chuàng)建訪問(wèn)的地址
URIBuilder uriBuilder = new URIBuilder(url);
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
// 創(chuàng)建http對(duì)象
HttpGet httpGet = new HttpGet(uriBuilder.build());
/**
* setConnectTimeout:設(shè)置連接超時(shí)時(shí)間僵闯,單位毫秒。
* setConnectionRequestTimeout:設(shè)置從connect Manager(連接池)獲取Connection
* 超時(shí)時(shí)間藤滥,單位毫秒鳖粟。這個(gè)屬性是新加的屬性,因?yàn)槟壳鞍姹臼强梢怨蚕磉B接池的拙绊。
* setSocketTimeout:請(qǐng)求獲取數(shù)據(jù)的超時(shí)時(shí)間(即響應(yīng)時(shí)間)向图,單位毫秒。 如果訪問(wèn)一個(gè)接口标沪,多少時(shí)間內(nèi)無(wú)法返回?cái)?shù)據(jù)榄攀,就直接放棄此次調(diào)用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpGet.setConfig(requestConfig);
// 設(shè)置請(qǐng)求頭
packageHeader(headers, httpGet);
// 創(chuàng)建httpResponse對(duì)象
CloseableHttpResponse httpResponse = null;
try {
// 執(zhí)行請(qǐng)求并獲得響應(yīng)結(jié)果
return getHttpClientResult(httpResponse, httpClient, httpGet);
} finally {
// 釋放資源
release(httpResponse, httpClient);
}
}
/**
* 發(fā)送post請(qǐng)求金句;不帶請(qǐng)求頭和請(qǐng)求參數(shù)
* @param url 請(qǐng)求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url) throws Exception {
return doPost(url, null, null);
}
/**
* 發(fā)送post請(qǐng)求檩赢;帶請(qǐng)求參數(shù)
*
* @param url 請(qǐng)求地址
* @param params 參數(shù)集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
return doPost(url, null, params);
}
/**
* 發(fā)送post請(qǐng)求;帶請(qǐng)求頭和請(qǐng)求參數(shù)
*
* @param url 請(qǐng)求地址
* @param headers 請(qǐng)求頭集合
* @param params 請(qǐng)求參數(shù)集合
* @return
* @throws Exception
*/
public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
// 創(chuàng)建httpClient對(duì)象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 創(chuàng)建http對(duì)象
HttpPost httpPost = new HttpPost(url);
/**
* setConnectTimeout:設(shè)置連接超時(shí)時(shí)間违寞,單位毫秒贞瞒。
* setConnectionRequestTimeout:設(shè)置從connect Manager(連接池)獲取Connection
* 超時(shí)時(shí)間,單位毫秒趁曼。這個(gè)屬性是新加的屬性军浆,因?yàn)槟壳鞍姹臼强梢怨蚕磉B接池的。
* setSocketTimeout:請(qǐng)求獲取數(shù)據(jù)的超時(shí)時(shí)間(即響應(yīng)時(shí)間)挡闰,單位毫秒乒融。 如果訪問(wèn)一個(gè)接口,多少時(shí)間內(nèi)無(wú)法返回?cái)?shù)據(jù)摄悯,就直接放棄此次調(diào)用赞季。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
// 設(shè)置請(qǐng)求頭
httpPost.setHeader("Cookie", "");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Accept","application/json, text/plain, */*");
httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
httpPost.setHeader("Content type","application/json");
packageHeader(headers, httpPost);
// 封裝請(qǐng)求參數(shù)
packageParam(params, httpPost);
// 創(chuàng)建httpResponse對(duì)象
CloseableHttpResponse httpResponse = null;
try {
// 執(zhí)行請(qǐng)求并獲得響應(yīng)結(jié)果
return getHttpClientResult(httpResponse, httpClient, httpPost);
} finally {
// 釋放資源
release(httpResponse, httpClient);
}
}
/**
* post請(qǐng)求通過(guò)jsonStr
* @param url
* @param reqJson
* @return
* @throws Exception
*/
public static HttpClientResult doPostJson(String url, String reqJson) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
httpPost.setHeader("HTTP Method","POST");
httpPost.setHeader("Connection","Keep-Alive");
httpPost.setHeader("Content-Type","application/json;charset=utf-8");
StringEntity entity = new StringEntity(reqJson);
entity.setContentType("application/json;charset=utf-8");
httpPost.setEntity(entity);
try {
response = httpClient.execute(httpPost);
return getHttpClientResult(response, httpClient, httpPost);
} finally {
release(response, httpClient);
}
}
/**
* 發(fā)送put請(qǐng)求;不帶請(qǐng)求參數(shù)
* @param url 請(qǐng)求地址
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url) throws Exception {
return doPut(url);
}
/**
* 發(fā)送put請(qǐng)求射众;帶請(qǐng)求參數(shù)
* @param url 請(qǐng)求地址
* @param params 參數(shù)集合
* @return
* @throws Exception
*/
public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPut.setConfig(requestConfig);
packageParam(params, httpPut);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpPut);
} finally {
release(httpResponse, httpClient);
}
}
/**
* 發(fā)送delete請(qǐng)求碟摆;不帶請(qǐng)求參數(shù)
* @param url 請(qǐng)求地址
* @return
* @throws Exception
*/
public static HttpClientResult doDelete(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete = new HttpDelete(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpDelete.setConfig(requestConfig);
CloseableHttpResponse httpResponse = null;
try {
return getHttpClientResult(httpResponse, httpClient, httpDelete);
} finally {
release(httpResponse, httpClient);
}
}
/**
* 發(fā)送delete請(qǐng)求晃财;帶請(qǐng)求參數(shù)
* @param url 請(qǐng)求地址
* @param params 參數(shù)集合
* @return
* @throws Exception
*/
public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
if (params == null) {
params = new HashMap<String, String>();
}
params.put("_method", "delete");
return doPost(url, params);
}
/**
* Description: 封裝請(qǐng)求頭
* @param params
* @param httpMethod
*/
public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
// 封裝請(qǐng)求頭
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
// 設(shè)置到請(qǐng)求頭到HttpRequestBase對(duì)象中
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
}
/**
* Description: 封裝請(qǐng)求參數(shù)
*
* @param params
* @param httpMethod
* @throws UnsupportedEncodingException
*/
public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
throws UnsupportedEncodingException {
// 封裝請(qǐng)求參數(shù)
if (params != null) {
List<NameValuePair> nvps = new ArrayList<>();
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 設(shè)置到請(qǐng)求的http對(duì)象中
httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
}
}
/**
* 獲得響應(yīng)結(jié)果
* @param httpResponse
* @param httpClient
* @param httpMethod
* @return
* @throws Exception
*/
public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
// 執(zhí)行請(qǐng)求
httpResponse = httpClient.execute(httpMethod);
// 獲取返回結(jié)果
if (httpResponse != null && httpResponse.getStatusLine() != null) {
String content = "";
if (httpResponse.getEntity() != null) {
content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
}
return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
}
return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
/**
* Description: 釋放資源
*
* @param httpResponse
* @param httpClient
* @throws IOException
*/
public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
// 釋放資源
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}