通过json发送
private String sendPostByJson(String url, Map<String, Object> params,
Map<String, String> headers) {
CloseableHttpClient httpclient = httpClient.getHttpClient();
HttpPost post = new HttpPost(url);
if (params != null && !params.isEmpty()) {
List<Header> tmpHeaders = new ArrayList<>();
tmpHeaders.add(
new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType()));
if (headers != null) {
headers.keySet().stream().forEach(key -> {
Header header = new BasicHeader(key, headers.get(key));
tmpHeaders.add(header);
});
}
post.setHeaders(tmpHeaders.toArray(new Header[] {}));
String json = ObjectMapperUtils.toJSON(params);
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
post.setEntity(entity);
}
int timeout = (int) TimeUnit.MINUTES.toMillis(3);
RequestConfig timeOutRequestConfig = RequestConfig.custom().setSocketTimeout(timeout)
.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).build();
post.setConfig(timeOutRequestConfig);
return execAndHandleThrowable(() -> {
CloseableHttpResponse response = httpclient.execute(post);
HttpEntity resEntity = response.getEntity();
return EntityUtils.toString(resEntity, StandardCharsets.UTF_8);
}, e -> logger.error(e.getMessage() + " when send json to server"));
}
|