此类为HttpClient,自己创建类复制进去即可
private static org.slf4j.Logger logger = LoggerFactory.getLogger(HttpClient.class);
private static String EMPTY_STR = null;
private static PoolingHttpClientConnectionManager cm;
private static String UTF_8 = "utf-8";
public static String httpPostRequest(PostParams postParams) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(CourtUtils.trim(postParams.getUrl()));
httpPost.setConfig(setTimedOut());
logger.info("开始调用httpPostRequest方法--------->");
Map<String ,Object> headers = postParams.getHeaders();
Params params = new Params();
params.setParams(postParams.getParams());
logger.info("设置请求头开始--------->");
for (Map.Entry<String, Object> param : headers.entrySet()) {
httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
}
logger.info("设置请求头结束--------->");
ArrayList<org.apache.http.NameValuePair> pairs = covertParams2NVPS(params);
httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
return getResult(httpPost);
}
public static RequestConfig setTimedOut() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(50000).setConnectionRequestTimeout(20000)
.setSocketTimeout(50000).build();
return requestConfig;
}
private static ArrayList<org.apache.http.NameValuePair> covertParams2NVPS(Params params) {
ArrayList<org.apache.http.NameValuePair> pairs = new ArrayList<org.apache.http.NameValuePair>();
Map<String, Object> params1 = params.getParams();
logger.info("设置参数开始------------>");
for (Map.Entry<String, Object> param : params1.entrySet()) {
pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
}
logger.info("设置参数完成------------>");
return pairs;
}
private static String getResult(HttpRequestBase request){
CloseableHttpClient httpClient = getHttpClient();
CloseableHttpResponse response = null;
int code = 0;
try {
response = httpClient.execute(request);
code = response.getStatusLine().getStatusCode();
if (code != Num.N200) {
logger.info("调用失败----------->"+code);
return EMPTY_STR;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity);
}
} catch (Exception e) {
logger.error("调用接口异常: "+request, e);
} finally {
try {
if(response!=null){
response.close();
}
} catch (IOException e1) {
logger.error("调用失败---->"+e1.getMessage());
}
}
return EMPTY_STR;
}
private static CloseableHttpClient getHttpClient() {
init();
return HttpClients.custom().setConnectionManager(cm).build();
}
private static void init() {
if (cm == null) {
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(1000);
cm.setDefaultMaxPerRoute(500);
}
}