public class HttpClientUtil {
private static final Log logger = LogFactory.getLog(HttpClientUtil.class);
public static String doPost(String url, Map<String, String> params) {
logger.info("doPost.url=" +url+",params"+ JSON.toJSONString(params));
PostMethod method = new PostMethod(url);
method.addRequestHeader("Content-Type","application/json;charset=utf-8");
method.addRequestHeader("Accept", "application/json;charset=utf-8");
// 重试策略;如果Http出错,默认三次重试
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
method.setRequestEntity(new ByteArrayRequestEntity(JSON.toJSONBytes(params)));
String response = "";
try {
HttpClient client = new HttpClient();
client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
response = method.getResponseBodyAsString();
}
logger.info("doPost.response=" + response);
} catch (Exception e) {
logger.error("执行HTTP Post请求[[" + url + "]]时,发生异常!", e);
} finally {
method.releaseConnection();
}
return response;
}
}