Java代码模拟一个Post请求
Java代码模拟一个Post请求
我们常用的http请求无非GET和POST。在springboot项目中,我们如果想要简单测试一段代码无非就是项目跑起来,然后在浏览器中通过输入url,看浏览器中(按F12)控制台是否响应成功,看IDEA控制台的打印内容以及日志。
但是在浏览器中输入url,GET请求很好模拟,无非是本机ip+服务端口+springboot项目中在controller层配置的@RequestMapping("/访问路径")。而POST请求就不是那么好模拟的了,因为POST请求一般包含参数,参数以JSON格式封装在请求体中,有其对应的请求头。那么POST请求该如何模拟呢?代码如下所示:
依赖:
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.24</version> </dependency>
这个依赖使用的目的是通过一个JSONObject的类封装我们的参数。然后剩下的依赖,在前面的HttpClient的学习笔记中有提到。
模拟Post请求代码如下:
import com.alibaba.fastjson.JSONObject;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.junit.Test;import java.io.IOException;public class PostTest { / * 模拟Post请求,进行url测试 */ @Test public void testPostRequest() { String url = "http://127.0.0.1:8081/business/user/record/query"; //请求ti JSONObject parammap = new JSONObject(); parammap.put("userid",123456); parammap.put("username", "xiaoming"); parammap.put("appname", "myapp"); parammap.put("queryDate","20220321"); String str = doPost(url, parammap.toJSONString()); // 输出响应内容 System.out.println(str); } public String doPost(String url ,String json) { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String res = ""; try { HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); post.setEntity(entity); response = httpClient.execute(post); res = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (IOException e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } return res; }}