HttpClientUtil-简洁多功能
[为了更好的阅读体验,请查看原文:https://www.cnblogs.com/maogen/p/util_httpclient.html]
本文主要是使用Java实现一个相对简洁的HttpClient工具类,具有以下功能:
buildQueryMessage
,根据请求Url和参数拼接为请求字符串doGet (url, params)
,请求参数可为空doPost (url, params, headers)
,请求参数和请求头可为空doPostJson (url, jsonStr)
doDelete (url, params)
,请求参数可为空doPut (url, params)
,请求参数可为空- ……
作者:晨星1032-博客园:https://www.cnblogs.com/maogen/
1. 依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
2. 代码
/**
* HttpClientUtil, get/post/delete/put
*/
@Slf4j
public class HttpClientUtil {
public static URI buildQueryMessage(String url, Map<String, Object> paramMap) {
String param = URLEncodedUtils.format(setHttpParams(paramMap), StandardCharsets.UTF_8);
return URI.create(url + "?" + param);
}
public static String doGet(String url) throws IOException {
return doGet(url, null);
}
public static String doGet(String url, Map<String, Object> paramMap) throws IOException {
log.info("doGet url=" + url);
HttpGet httpGet = new HttpGet();
return doRequest(httpGet, url, paramMap);
}
public static String doDelete(String url) throws IOException {
return doDelete(url, null);
}
public static String doDelete(String url, Map<String, Object> paramMap) throws IOException {
log.info("doDelete url=" + url);
HttpDelete httpDelete = new HttpDelete();
return doRequest(httpDelete, url, paramMap);
}
public static String doPut(String url) throws IOException {
return doPut(url, null);
}
public static String doPut(String url, Map<String, Object> paramMap) throws IOException {
log.info("doPut url=" + url);
HttpPut httpPut = new HttpPut();
return doRequest(httpPut, url, paramMap);
}
public static String doPost(String url) throws Exception {
return doPost(url, null, null);
}
public static String doPost(String url, Map<String, Object> paramMap) throws Exception {
return doPost(url, paramMap, null);
}
public static String doPost(String url, Map<String, Object> paramMap, Map<String, String> headerMap) throws Exception {
log.info("doPost url=" + url);
HttpPost httpPost = new HttpPost(url);
if (headerMap == null){
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
} else {
for (String key : headerMap.keySet()) {
httpPost.addHeader(key, headerMap.get(key));
}
}
if (null != paramMap && paramMap.size() > 0) {
List<NameValuePair> nameValPair = setHttpParams(paramMap);
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValPair, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new Exception("Failed to set request parameters {}" + e.getMessage() + e);
}
}
return executeHttp(httpPost);
}
public static String doPostJson(String url, String jsonStr) throws IOException {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
StringEntity entity = new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
return executeHttp(httpPost);
}
private static List<NameValuePair> setHttpParams(Map<String, Object> paramMap) {
List<NameValuePair> nameValPair = new ArrayList<>();
for (Map.Entry<String, Object> mapEntry : paramMap.entrySet()) {
nameValPair.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
}
return nameValPair;
}
private static String doRequest(HttpRequestBase httpBase, String url, Map<String, Object> paramMap) throws IOException {
if (paramMap == null) {
httpBase.setURI(URI.create(url));
} else {
httpBase.setURI(buildQueryMessage(url, paramMap));
}
return executeHttp(httpBase);
}
private static String executeHttp(HttpRequestBase httpBase) throws IOException {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setConnectionRequestTimeout(1000)
.setSocketTimeout(60000).build();
httpBase.setConfig(requestConfig);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
String result;
try {
httpResponse = httpClient.execute(httpBase);
HttpEntity entity = httpResponse.getEntity();
result = EntityUtils.toString(entity);
httpBase.abort();
} catch (IOException e) {
throw new IOException("Failed to execute request or get response " + e.getMessage() + e);
} finally {
closeHttpClientAndResp(httpClient, httpResponse);
}
return result;
}
private static void closeHttpClientAndResp(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) {
if (null != httpResponse) {
try {
httpResponse.close();
} catch (IOException e) {
log.error("Failed to close httpResponse {}", e.getLocalizedMessage(), e);
}
}
if (null != httpClient) {
try {
httpClient.close();
} catch (IOException e) {
log.error("Failed to close httpClient {}", e.getLocalizedMessage(), e);
}
}
}
}
3. 测试
public static void main(String[] args) throws Exception {
String url = "http://localhost:8866/test";
Map<String, Object> params = new HashMap<>();
params.put("response_type", "RESPONSE_TYPE");
params.put("client_id", "clientId");
params.put("redirect_uri", "http://localhost:8866/api/client");
String requestUrl = HttpClientUtil.buildQueryMessage(url, params).toString();
System.out.println(requestUrl);
HttpClientUtil.doGet(url);
HttpClientUtil.doGet(url, params);
HttpClientUtil.doDelete(url);
HttpClientUtil.doDelete(url, params);
HttpClientUtil.doPut(url);
HttpClientUtil.doPut(url, params);
HttpClientUtil.doPost(url);
HttpClientUtil.doPost(url, params);
HttpClientUtil.doPostJson(url, "{params:123, paaa:122}");
}
作者:晨星1032-博客园:https://www.cnblogs.com/maogen/