httpclient发送jPost请求的json格式参数【最简单的例子~~~~】
分类:
文章
•
2023-03-24 12:55:52
- 首先在postman中调用接口,是否可以调通。
- 在idea中写接口,明白需要那些数据,做什么,期望结果是什么【url,header,json入参】,【发送请求】【做断言】
- 创建一个httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault();类似于浏览器客户端,
- 创建一个请求对象HttpPost httpPost=new HttpPose(url);
- 添加请求头:httpPost.addHeader(“Content-type”, “application/json”);注意,如果请求头有很多类型,可以使用循环遍历请求头
- 添加json参数 [此处的json可以直接复制postman中入参json]
json="";
StringEntity postingString = new StringEntity(json);
httpPost.setEntity(postingString);
- 执行请求 HttpResponse httpResponse = httpClient.execute(httpPost);
- 做断言。