java HttpClient的工具类
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java HttpClient的工具类相关的知识,希望对你有一定的参考价值。
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
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.*;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Map;
public class HttpClientUtil {
private static Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class);
private static final CloseableHttpClient httpClient;
private static final String CHARSET = "UTF-8";
static {
RequestConfig config = RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(3000).setConnectionRequestTimeout(2000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy()).build();
}
/**
* 发送get请求
* @param url
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String get(String url) throws ClientProtocolException, IOException {
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity,CHARSET) : "";
} else {
throw new ClientProtocolException("Unexpected response status" + status);
}
}
};
HttpGet httpGet = new HttpGet(url);
String rsBody = httpClient.execute(httpGet,responseHandler);
return rsBody;
}
/**
* 发送post请求
* @param url
* @param param
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static String sendPost(String url, String param) throws ClientProtocolException, IOException {
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity,"UTF-8") : "";
} else {
throw new ClientProtocolException("Unexpected response status" + status);
}
}
};
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(param, CHARSET));
String rsBody = httpClient.execute(httpPost,responseHandler);
return rsBody;
}
/**
* 请求http的公共方法
* @param url
* @param params
* @return
* @throws Exception
*/
public static String httpPost(String url ,Map<String,String> params) throws Exception{
String result = null;
//记录日志
StringBuilder sb = new StringBuilder();
sb.append("HTTP请求地址:");
sb.append(url);
sb.append(",");
sb.append("参数为:");
if(params != null){
for(String key : params.keySet()){
sb.append(key);
sb.append(":");
sb.append(params.get(key));
sb.append(",");
}
}
LOG.debug(sb.toString());
//构造参数
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
RequestBuilder builder = RequestBuilder.post().setUri(url);
// builder.addHeader("Content-type" , "text/html; charset=utf-8");
if(params != null){
for(String key : params.keySet()){
builder.addParameter(key, params.get(key));
}
}
//设置超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000).setConnectTimeout(1000).build();
builder.setConfig(requestConfig);
HttpUriRequest httpUriRequest = builder.build();
try {
long start = System.currentTimeMillis();
CloseableHttpResponse response = closeableHttpClient.execute(httpUriRequest);
long end = System.currentTimeMillis() -start;
sb.append(" 响应时间 = " + String.valueOf(end) + "ms , statuscode : "+response.getStatusLine().getStatusCode());
LOG.debug(sb.toString());
HttpEntity entity = response.getEntity();
if(end > 3000){
LOG.error(sb.toString());
}
//状态码不是200表示发生异常。记录错误日志。
if(response.getStatusLine().getStatusCode() != 200){
LOG.error(sb.toString());
}
//获取结果,并且设置编码集
result = EntityUtils.toString(entity,CHARSET);
sb.append(",result:" + result);
LOG.debug(sb.toString());
return result;
} catch (ClientProtocolException e) {
LOG.warn("http请求发生异常", e);
throw e;
} catch (IOException e) {
LOG.warn("http请求发生异常", e);
throw e;
}finally{
if(closeableHttpClient != null){
try {
closeableHttpClient.close();
} catch (IOException e) {
LOG.warn("http请求发生异常", e);
throw e;
}
}
}
}
}
以上是关于java HttpClient的工具类的主要内容,如果未能解决你的问题,请参考以下文章
Java HttpClient4.2.x版本getpost请求工具类
Java生成证书工具类 InstallCert.java解决httpClient访问https出错:PKIX path building failed