概述
public class HttpUtils {
private static String CHARSET = "UTF-8";
//请求超时时间
public static int socketTimeout = 30000;
//传输超时时间
public static int connectTimeout = 30000;
private static final String HTTP = "http";
private static final String HTTPS = "https";
private static SSLConnectionSocketFactory sslsf = null;
private static PoolingHttpClientConnectionManager cm = null;
private static SSLContextBuilder builder = null;
static {
try {
builder = new SSLContextBuilder();
// 全部信任 不做身份鉴定
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
});
sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register(HTTP, new PlainConnectionSocketFactory())
.register(HTTPS, sslsf)
.build();
cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(200);
} catch (Exception e) {
e.printStackTrace();
}
}
public static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(cm)
.setConnectionManagerShared(true)
.build();
return httpClient;
}
public static RequestConfig getConfig(){
return RequestConfig.custom().setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout).build();
}
public static <T>T sendGet(String url, Map<String,String> params, Map<String,String> headerMap, Class<T> javaType) {
String apiUrl = url;
StringBuffer param =new StringBuffer();
int i =0;
for (String key : params.keySet()) {
if (i ==0){
param.append("?");
}else{
param.append("&");
}
param.append(key).append("=").append(params.get(key));
i++;
}
apiUrl += param;
CloseableHttpClient httpclient = getHttpClient();;
CloseableHttpResponse response =null;
try {
HttpGet httpGet =new HttpGet(apiUrl);
httpGet.setConfig(getConfig());
httpGet.setHeader("Content-Type", "application/json");
if (httpGet != null && headerMap.size() != 0) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
//执行get请求
response = httpclient.execute(httpGet);
//返回结果
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
return httpOk(response,javaType);
} else {
return readHttpResponse(response,javaType);
}
}catch (IOException e) {
e.printStackTrace();
}finally {
if (response !=null) {
try {
response.close();
EntityUtils.consume(response.getEntity());
}catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* httpClient post请求
* @param reqJson json数据
* @return 可能为空 需要处理
* @throws Exception
*/
public static <T> T sendPost(String url, String reqJson, Map<String, String> headerMap, Class<T> javaType) {
CloseableHttpClient httpClient = null;
HttpResponse httpResponse=null;
try {
httpClient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(getConfig());
httpPost.setHeader("Content-Type", "application/json");
if (headerMap != null && headerMap.size() != 0) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
StringEntity entity = new StringEntity(reqJson, CHARSET);
entity.setContentEncoding(CHARSET);
httpPost.setEntity(entity);
//执行请求
httpResponse = httpClient.execute(httpPost);
//返回结果解析
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
return httpOk(httpResponse,javaType);
} else {
return readHttpResponse(httpResponse,javaType);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpClient != null) {
try {
httpClient.close();
EntityUtils.consume(httpResponse.getEntity());
}catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 发送 SSL POST 请求(HTTPS),K-V形式
* @param
*/
public static String doPostSSL(String url, Map<String,String> params) {
CloseableHttpClient httpClient = getHttpClient();
HttpPost httpPost =new HttpPost(url);
CloseableHttpResponse response =null;
String result =null;
try {
httpPost.setConfig(getConfig());
List pairList =new ArrayList(params.size());
for (Map.Entry entry : params.entrySet()) {
NameValuePair pair =new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName(CHARSET)));
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity !=null) {
result = EntityUtils.toString(entity,CHARSET);
}
}catch (Exception e) {
e.printStackTrace();
}finally {
if (response !=null) {
try {
EntityUtils.consume(response.getEntity());
}catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* 发送 SSL POST 请求(HTTPS),JSON形式
* @param
*/
public static String doPostSSL(String url, Object json) {
CloseableHttpClient httpClient =getHttpClient();
HttpPost httpPost =new HttpPost(url);
CloseableHttpResponse response =null;
String result =null;
try {
httpPost.setConfig(getConfig());
StringEntity stringEntity =new StringEntity(json.toString(),CHARSET);// 解决中文乱码问题
stringEntity.setContentEncoding(CHARSET);
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
HttpEntity entity = response.getEntity();
if (entity !=null) {
result = EntityUtils.toString(entity,CHARSET);
}
}catch (Exception e) {
e.printStackTrace();
}finally {
if (response !=null) {
try {
EntityUtils.consume(response.getEntity());
}catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
* 原生字符串发送put请求
* @param url
* @param token
* @param jsonStr
* @return
**/
public static String doPut(String url, String token, String jsonStr) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut =new HttpPut(url);
httpPut.setConfig(getConfig());
httpPut.setHeader("Content-type","application/json");
httpPut.setHeader("DataEncoding",CHARSET);
httpPut.setHeader("access-token", token);
CloseableHttpResponse httpResponse =null;
try {
httpPut.setEntity(new StringEntity(jsonStr));
httpResponse = httpClient.execute(httpPut);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
return result;
}catch (ClientProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
if (httpResponse !=null) {
try {
httpResponse.close();
}catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 发送delete请求
* @param url
* @param token
* @param jsonStr
* @return
**/
public static String doDelete(String url, String token, String jsonStr) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpDelete httpDelete =new HttpDelete(url);
httpDelete.setConfig(getConfig());
httpDelete.setHeader("Content-type","application/json");
httpDelete.setHeader("DataEncoding",CHARSET);
httpDelete.setHeader("access-token", token);
CloseableHttpResponse httpResponse =null;
try {
httpResponse = httpClient.execute(httpDelete);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
return result;
}catch (ClientProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
if (httpResponse !=null) {
try {
httpResponse.close();
}catch (IOException e) {
e.printStackTrace();
}
}
if (null != httpClient) {
try {
httpClient.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
private static
<T>T httpOk(HttpResponse httpResponse,Class<T> javaType){
HttpEntity resEntity = httpResponse.getEntity();
String result = null;
try {
result = EntityUtils.toString(resEntity);
ObjectMapper mapper=new ObjectMapper();
T t = mapper.readValue(result, javaType);
return t;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static <T>T readHttpResponse(HttpResponse httpResponse, Class<T> javaType)
throws ParseException, IOException {
StringBuilder builder = new StringBuilder();
Map<String,String> resultMap= Maps.newHashMap();
// 获取响应消息实体
HttpEntity entity = httpResponse.getEntity();
// 响应状态
resultMap.put("code",httpResponse.getStatusLine().toString());
HeaderIterator iterator = httpResponse.headerIterator();
while (iterator.hasNext()) {
builder.append("t" + iterator.next());
}
resultMap.put("message",builder.toString());
builder.delete(0,builder.length());
// 判断响应实体是否为空
if (entity != null) {
String responseString = EntityUtils.toString(entity);
builder.append(responseString.replace("rn", ""));
}
resultMap.put("errorData",builder.toString());
//转成实体类
String toJSON = JSONObject.toJSON(resultMap).toString();
ObjectMapper mapper=new ObjectMapper();
return mapper.readValue(toJSON, javaType);
}
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency>注:sendPost和sendGet 测试是OK的 其它的方法没有测试过
HttpUtils.sendPost(url,json, healthRequest.getHeader(), RESTfulResultVO.class);HttpUtils.sendGet(url,Maps.newHashMap(),healthRequest.getHeader(),RESTfulResultVO.class);
最后
以上就是幸福战斗机为你收集整理的http 工具类的全部内容,希望文章能够帮你解决http 工具类所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复