HttpClient工具类封装
package com.raysdata.iothub.server.util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* HttpClient4.3工具类
*
* @author hang.luo
*/
public class HttpClientUtils {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class); // 日志记录
private static RequestConfig requestConfig = null;
public static final String default_Charset = "UTF-8";
static {
// 设置请求和传输超时时间
requestConfig = RequestConfig.custom().setSocketTimeout(60 * 1000).setConnectTimeout(60 * 1000).build();
}
/**
* post请求传输json参数
* @param headers
* @param url
* @param jsonParam
* @param timeOut
* @return
*/
public static JSONObject httpPost(Map<String, String> headers, String url, Object jsonParam, Integer timeOut) {
logger.info("httpPost start:headers={},url={},jsonParam={},timeOut={}",headers,url,jsonParam,timeOut);
// post请求返回结果
JSONObject jsonResult = null;
try{
String str=httpPostStr(headers,url,jsonParam,timeOut);
jsonResult = JSONObject.parseObject(str);
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}
return jsonResult;
}
public static JSONArray httpPostList(Map<String, String> headers, String url, Object jsonParam, Integer timeOut) {
logger.info("httpPost start:headers={},url={},jsonParam={},timeOut={}",headers,url,jsonParam,timeOut);
// post请求返回结果
JSONArray jsonResult = null;
try{
String str=httpPostStr(headers,url,jsonParam,timeOut);
jsonResult = JSONArray.parseArray(str);
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}
return jsonResult;
}
public static String httpPostStr(Map<String, String> headers, String url, Object jsonParam, Integer timeOut) {
logger.info("httpPost start:headers={},url={},jsonParam={},timeOut={}",headers,url,jsonParam,timeOut);
// post请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
String str = "";
HttpPost httpPost = new HttpPost(url);
// 设置请求和传输超时时间
if (timeOut != null) {
RequestConfig rC = RequestConfig.custom().setSocketTimeout(timeOut * 1000).setConnectTimeout(timeOut * 1000).build();
httpPost.setConfig(rC);
}
httpPost.setConfig(requestConfig);
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
try {
if (null != jsonParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
CloseableHttpResponse result = httpClient.execute(httpPost);
// 请求发送成功,并得到响应
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK||result.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
try {
// 读取服务器返回过来的json字符串数据
str = EntityUtils.toString(result.getEntity(), "utf-8");
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
logger.error("post请求提交失败:" + url, e);
} finally {
httpPost.releaseConnection();
}
return str;
}
/**
* post请求传输json参数
*
* @param url url地址
* @param jsonParam 参数
* @param timeOut 超时时间(秒)
* @return
*/
public static JSONObject httpPost(String url, JSONObject jsonParam, Integer timeOut) {
return HttpClientUtils.httpPost(null, url, jsonParam, timeOut);
}
public static JSONObject httpPost(String url, JSONObject jsonParam) {
return HttpClientUtils.httpPost(null, url, jsonParam, null);
}
public static JSONObject httpPost(String url, String strParam) {
return HttpClientUtils.httpPost(null, url, strParam, null);
}
public static JSONObject httpPost(Map<String, String> headers,String url, JSONObject jsonParam) {
return HttpClientUtils.httpPost(headers, url, jsonParam, null);
}
public static JSONObject httpPost(Map<String, String> headers,String url, String strParam) {
return HttpClientUtils.httpPost(headers, url, strParam, null);
}
public static JSONArray httpPostList(String url, JSONObject jsonParam, Integer timeOut) {
return HttpClientUtils.httpPostList(null, url, jsonParam, timeOut);
}
public static JSONArray httpPostList(String url, JSONObject jsonParam) {
return HttpClientUtils.httpPostList(null, url, jsonParam, null);
}
public static JSONArray httpPostList(String url, String strParam) {
return HttpClientUtils.httpPostList(null, url, strParam, null);
}
public static JSONArray httpPostList(Map<String, String> headers,String url, JSONObject jsonParam) {
return HttpClientUtils.httpPostList(headers, url, jsonParam, null);
}
public static JSONArray httpPostList(Map<String, String> headers,String url, String strParam) {
return HttpClientUtils.httpPostList(headers, url, strParam, null);
}
/**
* 发送get请求
*
* @param url 路径
* @return
*/
public static String httpGetStr(Map<String, String> headers, String url, Map<String, String> params, Integer timeOut) throws Exception {
logger.info("httpGet start:headers={},url={},params={},timeOut={}",headers,url,params,timeOut);
// get请求返回结果
String strResult="";
CloseableHttpClient client = HttpClients.createDefault();
// 发送get请求
String requestUrl = makeUrl(url, params);
HttpGet request = new HttpGet(requestUrl);
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
request.setHeader(entry.getKey(), entry.getValue());
}
}
//request.setHeader("Content-Type", "application/json");
if (timeOut != null) {
RequestConfig rC = RequestConfig.custom().setSocketTimeout(timeOut * 1000).setConnectTimeout(timeOut * 1000).build();
request.setConfig(rC);
} else {
request.setConfig(requestConfig);
}
try {
CloseableHttpResponse response = client.execute(request);
// 请求发送成功,并得到响应
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 读取服务器返回过来的json字符串数据
HttpEntity entity = response.getEntity();
strResult = EntityUtils.toString(entity, "utf-8");
// 把json字符串转换成json对象
logger.info("httpGet end,result={}",strResult);
} else {
logger.error("get请求提交失败:" + url);
}
} catch (IOException e) {
logger.error("get请求提交失败:" + url, e);
} finally {
request.releaseConnection();
}
return strResult;
}
public static JSONObject httpGet(Map<String, String> headers, String url, Map<String, String> jsonParam, Integer timeOut) {
logger.info("httpPost start:headers={},url={},jsonParam={},timeOut={}",headers,url,jsonParam,timeOut);
// post请求返回结果
JSONObject jsonResult = null;
try{
String str=httpGetStr(headers,url,jsonParam,timeOut);
jsonResult = JSONObject.parseObject(str);
} catch (Exception e) {
logger.error("get请求提交失败:" + url, e);
}
return jsonResult;
}
public static JSONArray httpGetList(Map<String, String> headers, String url, Map<String, String> jsonParam, Integer timeOut) {
logger.info("httpPost start:headers={},url={},jsonParam={},timeOut={}",headers,url,jsonParam,timeOut);
// post请求返回结果
JSONArray jsonResult = null;
try{
String str=httpGetStr(headers,url,jsonParam,timeOut);
jsonResult = JSONArray.parseArray(str);
} catch (Exception e) {
logger.error("get请求提交失败:" + url, e);
}
return jsonResult;
}
/**
* 发送get请求
*
* @param url 路径
* @return
*/
public static JSONObject httpGet(String url, Map<String, String> params, Integer timeOut) throws Exception {
return HttpClientUtils.httpGet(null, url, params, timeOut);
}
public static JSONArray httpGetList(String url, Map<String, String> params, Integer timeOut) throws Exception {
return HttpClientUtils.httpGetList(null, url, params, timeOut);
}
public static String makeUrl(String url, Map<String, String> params) throws UnsupportedEncodingException {
StringBuffer sb = new StringBuffer();
sb.append(url).append("?t=").append(System.currentTimeMillis());
if (params != null) {
Set<Entry<String, String>> entries = params.entrySet();
for (Entry<String, String> entry : entries) {
if (entry != null && entry.getValue() != null) {
sb.append("&").append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), default_Charset));
}
}
}
return sb.toString();
}
public static JSONObject httpPut(Map<String, String> headers, String url, Object jsonParam) {
return HttpClientUtils.httpPut(headers,url,jsonParam,null);
}
/**
* post请求传输json参数
* @param headers
* @param url
* @param jsonParam
* @param timeOut
* @return
*/
public static JSONObject httpPut(Map<String, String> headers, String url, Object jsonParam, Integer timeOut) {
logger.info("httpPut start:headers={},url={},params={},timeOut={}",headers,url,jsonParam,timeOut);
// put请求返回结果
CloseableHttpClient httpClient = HttpClients.createDefault();
JSONObject jsonResult = null;
HttpPut httpPut = new HttpPut(url);
// 设置请求和传输超时时间
if (timeOut != null) {
RequestConfig rC = RequestConfig.custom().setSocketTimeout(timeOut * 1000).setConnectTimeout(timeOut * 1000).build();
httpPut.setConfig(rC);
}
httpPut.setConfig(requestConfig);
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
httpPut.setHeader(entry.getKey(), entry.getValue());
}
}
try {
if (null != jsonParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPut.setEntity(entity);
}
CloseableHttpResponse result = httpClient.execute(httpPut);
// 请求发送成功,并得到响应
if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String str = "";
try {
// 读取服务器返回过来的json字符串数据
str = EntityUtils.toString(result.getEntity(), "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(str);
logger.info("httpPut end,result={}",jsonResult);
} catch (Exception e) {
logger.error("put请求提交失败:" + url, e);
}
}
} catch (IOException e) {
logger.error("put请求提交失败:" + url, e);
} finally {
httpPut.releaseConnection();
}
return jsonResult;
}
/**
* post请求传输json参数
* @param headers
* @param url
* @param params
* @param timeOut
* @return
*/
public static JSONObject httpDelete(Map<String, String> headers, String url, Map<String, String> params, Integer timeOut) {
logger.info("httpDelete start:headers={},url={},params={},timeOut={}",headers,url,params,timeOut);
// get请求返回结果
JSONObject jsonResult = null;
CloseableHttpClient client = HttpClients.createDefault();
// 发送get请求
String requestUrl = null;
try {
requestUrl = makeUrl(url, params);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpDelete request = new HttpDelete(requestUrl);
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
request.setHeader(entry.getKey(), entry.getValue());
}
}
request.setHeader("Content-Type", "application/json");
if (timeOut != null) {
RequestConfig rC = RequestConfig.custom().setSocketTimeout(timeOut * 1000).setConnectTimeout(timeOut * 1000).build();
request.setConfig(rC);
} else {
request.setConfig(requestConfig);
}
try {
CloseableHttpResponse response = client.execute(request);
// 请求发送成功,并得到响应
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 读取服务器返回过来的json字符串数据
HttpEntity entity = response.getEntity();
String strResult = EntityUtils.toString(entity, "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(strResult);
logger.info("httpDelete end,result={}",jsonResult);
} else {
logger.error("delete请求提交失败:" + url);
}
} catch (IOException e) {
logger.error("delete请求提交失败:" + url, e);
} finally {
request.releaseConnection();
}
return jsonResult;
}
public static JSONObject httpDelete(Map<String, String> headers, String url, Map<String, String> params) {
return HttpClientUtils.httpDelete(headers,url,params,null);
}
}
对该博客有疑问,可以加qq 973645236 或者私信本人解决问题