直接上代码
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
// 将内容放请求对象中
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
if(response != null && response.getEntity() != null) {
//设置响应返回的编码格式及转字符串
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
}else{
resultString = null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(response != null) {
response.close();
}
} catch (IOException e) {
logger.error("http请求失败:", e);
}
}
return resultString;
}
网友评论