public void send(String data){
StringEntity content = new StringEntity(data, ContentType.create("application/json","UTF-8"));
HttpPost httpPost = new HttpPost("http://...");
httpPost.setEntity(content);
httpPost.addHeader("connection","keep-alive");
httpPost.addHeader("content-type","application/json");
CloseableHttpResponse response = this.httpClient.execute(httpPost);
logger.debug("sent:\n"+data);
try{
StringBuilder sb = new StringBuilder("response:\n");
HeaderIterator it = response.headerIterator();
while(it.hasNext()){
sb.append(it.next()+"\n");
}
String responseBody = EntityUtils.toString(response.getEntity());
sb.append(responseBody);
logger.debug(sb.toString());
}finally{
response.close();
}
}
注意点:默认HttpClient.execute如对方不响应,会无限等待,需要设置timeout,比如:
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();
this.httpClient = HttpClients.custom()
.setDefaultRequestConfig(defaultRequestConfig)
.build();
另外具体request,比如HttpPost也可以覆盖这个设置