使用HttpClient发送post请求时传递json格式的参数
作者:互联网
-
java
-
// 接口测试-处理json格式的post请求
-
public static String doPostJson(String url,String json) {
-
// 创建连接池
-
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
-
ResponseHandler<String> responseHandler = new BasicResponseHandler();
-
// 声明呀一个字符串用来存储response
-
String result;
-
// 创建httppost对象
-
HttpPost httpPost = new HttpPost(url);
-
// 给httppost对象设置json格式的参数
-
StringEntity httpEntity = new StringEntity(json,"utf-8");
-
// 设置请求格式
-
httpPost.setHeader("Content-type","application/json");
-
// 传参
-
httpPost.setEntity(httpEntity);
-
// 发送请求,并获取返回值
-
try {
-
CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
-
//返回结果 响应码200
-
return response.getStatusLine().getStatusCode();
-
response.close();
-
} catch (IOException e) {
-
// TODO Auto-generated catch block
-
e.printStackTrace();
-
}
-
return "error";
-
}
标签:String,json,httpPost,格式,new,post,response,HttpClient 来源: https://blog.csdn.net/qq_38480786/article/details/112465470