使用依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
工具类
public class HttpClientUtil {
private static HttpClientUtil httpClient;
private final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private final PoolingHttpClientConnectionManager cm;
private final RequestConfig reqConfig;
private final HttpClientBuilder clientBuilder;
private final Semaphore semaphore = new Semaphore(300);
{
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainsf)
.register("https", sslsf)
.build();
cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(1000);
cm.setDefaultMaxPerRoute(1000);
reqConfig = RequestConfig.custom()
.setConnectionRequestTimeout(15000)
.setConnectTimeout(15000)
.setSocketTimeout(15000)
.setExpectContinueEnabled(false)
.build();
clientBuilder = HttpClients.custom();
clientBuilder.setDefaultRequestConfig(reqConfig);
clientBuilder.setConnectionManager(cm);
}
public String getHttpResponseBody(String url, Map<String, String> headerMap) {
try {
semaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
HttpGet request = new HttpGet(url);
return requestExecute(request, headerMap);
}
public ByteArrayOutputStream getHttpResponseIs(String url, Map<String, String> headerMap) {
try {
semaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
HttpGet request = new HttpGet(url);
return requestExecuteByte(request, headerMap);
}
public String postHttpResponseBody(String url, Map<String, String> headerMap, Object paramBody) {
try {
semaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
HttpPost request = new HttpPost(url);
if (paramBody != null) {
String bodyStr = JSON.toJSONString(paramBody);
request.setEntity(new StringEntity(bodyStr, ContentType.APPLICATION_JSON));
}
return requestExecute(request, headerMap);
}
public String postHttpResponseXmlBody(String url, Map<String, String> headerMap, String paramBody) {
try {
semaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
HttpPost request = new HttpPost(url);
if (paramBody != null) {
request.setEntity(new StringEntity(paramBody, ContentType.APPLICATION_XML));
}
return requestExecute(request, headerMap);
}
public String putHttpResponseBody(String url, Map<String, String> headerMap, Object paramBody) {
try {
semaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
String bodyStr = JSON.toJSONString(paramBody);
HttpPut request = new HttpPut(url);
request.setEntity(new StringEntity(bodyStr, ContentType.APPLICATION_JSON));
return requestExecute(request, headerMap);
}
public String postFileHttpResponseBody(String url, String fileField, byte[] bytes,
Map<String, String> headerMap, Object paramBody) {
headerMap.put("Content-Type", null);
try {
semaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(StandardCharsets.UTF_8);
JSONObject jsonObject = (JSONObject) JSON.toJSON(paramBody);
if (bytes != null) {
String filename = jsonObject.getString("filename");
filename = filename == null ? "" : filename;
ContentType contentType = ContentType.create("application/octet-stream", "UTF-8");
builder.addBinaryBody(fileField, bytes, contentType, filename);
}
final ContentType contentType = ContentType.create("text/plain", "UTF-8");
jsonObject.forEach((k, v) -> {
if (v == null) return;
StringBody stringBody = new StringBody(v.toString(), contentType);
builder.addPart(k, stringBody);
});
HttpPost request = new HttpPost(url);
request.setEntity(builder.build());
return requestExecute(request, headerMap);
}
public String postHttpFormResponseBody(String url, Map<String, String> headerMap, Object params) {
try {
semaphore.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
ArrayList<BasicNameValuePair> basicNameValuePairs = new ArrayList<>();
if (params instanceof Map) {
Set<Map.Entry<String, String>> entries = ((Map) params).entrySet();
for (Map.Entry<String, String> entry : entries) {
basicNameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
} else {
ReflectionUtils.doWithFields(params.getClass(), field -> {
field.setAccessible(true);
Object val = field.get(params);
if (val != null) {
basicNameValuePairs.add(new BasicNameValuePair(field.getName(), val.toString()));
}
});
}
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(basicNameValuePairs, StandardCharsets.UTF_8);
HttpPost request = new HttpPost(url);
request.setEntity(urlEncodedFormEntity);
headerMap.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
return requestExecute(request, headerMap);
}
public String createGetRequestUrl(ApiBaseReq reqParam, String platform) {
String apiUrl = reqParam.getApiUrl();
JSONObject json = (JSONObject) JSONObject.toJSON(reqParam);
return this.createGetRequestUrl(json, apiUrl, platform);
}
public String createGetRequestUrl(JSONObject reqJson, String apiUrl, String platform) {
String params = reqJson.entrySet().stream().filter(x -> x.getValue() != null && !"null".equals(x.getValue()))
.map(x -> {
try {
return this.joinParam(x.getKey(), x.getValue(), platform);
} catch (UnsupportedEncodingException e) {
logger.error("createGetRequestUrl UnsupportedEncodingException:", e);
return null;
}
}).collect(Collectors.joining("&"));
if (!apiUrl.endsWith("?") && apiUrl.contains("=")) return apiUrl + "&" + params;
return apiUrl.endsWith("?") ? apiUrl + params : apiUrl + "?" + params;
}
private String joinParam(Object key, Object val, String platform) throws UnsupportedEncodingException {
if (val instanceof JSONArray) {
if ("BL_BL".equalsIgnoreCase(platform)) {
return key + "=" + val.toString().replaceAll("\\[|\\]|\"", "");
}
return key + "=" + URLEncoder.encode(val.toString(), "utf-8");
} else if (val instanceof JSONObject) {
return key + "=" + URLEncoder.encode(val.toString(), "utf-8");
} else {
return key + "=" + val;
}
}
private String requestExecute(HttpRequestBase request, Map<String, String> headerMap) {
setHeaders(request, headerMap);
CloseableHttpClient httpClient = clientBuilder.build();
HttpClientContext localContext = HttpClientContext.create();
CloseableHttpResponse httpResp = null;
try {
httpResp = httpClient.execute(request, localContext);
if (httpResp == null) {
logger.error("【requestExecute】请求失败 httpResp is null");
return null;
}
int statusCode = httpResp.getStatusLine().getStatusCode();
if (httpResp.getStatusLine().getStatusCode() != 200) {
logger.error("【requestExecute】请求失败 statusCode:{}", statusCode);
return null;
}
if (httpResp.getEntity() == null) return null;
return getResponseStr(httpResp);
} catch (Exception e) {
logger.error("【httpClient】 requestExecute Exception:{}", e.getMessage());
return null;
} finally {
StreamClose.close(httpResp);
request.releaseConnection();
clientClose();
}
}
private ByteArrayOutputStream requestExecuteByte(HttpRequestBase request, Map<String, String> headerMap) {
setHeaders(request, headerMap);
CloseableHttpClient httpClient = clientBuilder.build();
HttpClientContext localContext = HttpClientContext.create();
CloseableHttpResponse httpResp = null;
try {
httpResp = httpClient.execute(request, localContext);
if (httpResp == null) {
logger.error("【requestExecuteByte】请求失败 httpResp is null");
return null;
}
int statusCode = httpResp.getStatusLine().getStatusCode();
if (httpResp.getStatusLine().getStatusCode() != 200) {
logger.error("【requestExecuteByte】请求失败 statusCode:{}", statusCode);
return null;
}
if (httpResp.getEntity() == null) return null;
ByteArrayOutputStream aos = new ByteArrayOutputStream();
IOUtils.copy(httpResp.getEntity().getContent(), aos);
return aos;
} catch (Exception e) {
logger.error("【httpClient】 requestExecuteByte Exception:{}", e.getMessage());
return null;
} finally {
StreamClose.close(httpResp);
request.releaseConnection();
clientClose();
}
}
private void setHeaders(HttpRequestBase httpReq, Map<String, String> headerMap) {
httpReq.setConfig(reqConfig);
if (headerMap == null) return;
if (!headerMap.containsKey("Content-Type")) {
httpReq.setHeader("Content-Type", "application/json;charset=UTF-8");
}
headerMap.forEach((k, v) -> {
if (v == null || k == null) return;
httpReq.setHeader(k, v);
});
}
private void clientClose() {
cm.closeExpiredConnections();
cm.closeIdleConnections(30, TimeUnit.SECONDS);
semaphore.release();
}
private String getResponseStr(CloseableHttpResponse httpResp) {
InputStream is = null;
try {
is = httpResp.getEntity().getContent();
String charsetName = getCharsetName(httpResp);
return IOUtils.toString(is, charsetName);
} catch (IOException e) {
logger.error("getResponseStr IOException:{}", e.getMessage());
} finally {
StreamClose.close(is);
}
return null;
}
private String getCharsetName(CloseableHttpResponse httpResp) {
String value = httpResp.getEntity().getContentType().getValue().trim();
String[] contentTypes = value.split(";");
String charsetName = StandardCharsets.UTF_8.displayName();
for (String type : contentTypes) {
if (!type.trim().startsWith("charset")) continue;
String[] split = type.split("=");
return split[1];
}
return charsetName;
}
public static HttpClientUtil getInstance() {
if (httpClient != null) return httpClient;
synchronized (HttpClientUtil.class) {
if (httpClient != null) return httpClient;
httpClient = new HttpClientUtil();
}
return httpClient;
}
private HttpClientUtil() {
}
}