Post:
public void httpDoPost(String url, JSONObject params) {
//创建默认Client实例
CloseableHttpClient client = HttpClients.createDefault();
//创建post请求实例
HttpPost httpPost =new HttpPost(url);
//添加请求头信息
httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
try {
//传递参数 防止乱码
httpPost.setEntity(new StringEntity(params.toJSONString(), "utf-8"));
//得到响应内容 包含状态码,头信息等
CloseableHttpResponse resp = client.execute(httpPost);
// 获取响应entity,等同于response中body的内容
HttpEntity respEntity = resp.getEntity();
try{
//将响应内容转换成String输出
String result = EntityUtils.toString(respEntity, "UTF-8");
}final{
//关闭响应接收
resp.close();
}
}catch(Exception e){
new RuntimeException(e);
}final{
client.close();
}
}