如标题所示,这是一个方法 :-)
/**
* json参数方式POST提交
*
* @param url需要访问的路径
* @param params传入的json格式的参数
* @return
*/
public static String doPostJson(String url, JSONObject params) {
String strResult = "";
// 1. 获取默认的client实例
CloseableHttpClient client = HttpClients.createDefault();
// 2. 创建httppost实例
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);
try {
// 7. 获取响应entity
HttpEntity respEntity = resp.getEntity();
strResult = EntityUtils.toString(respEntity, "UTF-8");
} finally {
resp.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return strResult;
}