使用POST方式发送JSON串:
public String sendRequestByPost(String targetURL, String jsonStr) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(targetURL);
// 默认是ISO-8859-1, 这里必须设置成UTF-8否则中文会乱码
StringEntity entity = new StringEntity(jsonStr, ContentType.create("plain/text", Consts.UTF_8));
//entity.setChunked(true);
httpPost.setEntity(entity);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
HttpEntity resEntity = response.getEntity();
byte[] responseBody = EntityUtils.toByteArray(resEntity);
String result = new String(responseBody, "UTF-8");
EntityUtils.consume(resEntity);
logger.debug("\n\tSend msg:{} \n\t to:{} \n\t result:{}", jsonStr, targetURL, result);
return result;
}
}