Java语言搭建接口自动化框架学习(单接口请求和响应)
程序员文章站
2022-06-23 18:56:10
代码实现单接口请求和响应maven项目:pom.xml导入httpclient依赖模拟发送get请求响应报文获取模拟发送post请求maven项目:pom.xml导入httpclient依赖org.apache.httpcomponents httpclient &l...
代码实现单接口请求和响应
maven项目:pom.xml导入httpclient依赖
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
</dependencies>
模拟发送get请求
//1、设置以get请求方式请求url
HttpGet get = new HttpGet("测试的接口地址");
//2、设置请求头和入参(如有),模拟请求报文
get.setHeader("请求头字段", "字段值");
//3、代码模拟发送请求前要创建一个发送请求的客户端
HttpClient httpClient = HttpClients.createDefault();
//4、发送请求并获取响应报文
HttpResponse httpResponse = httpClient.execute(get);
响应报文获取
//5、响应报文格式化拆解:响应头+响应体+响应状态码
Header[] allHeaders = httpResponse.getAllHeaders();
System.out.println("响应头:"+Arrays.toString(allHeaders));
HttpEntity httpEntity = httpResponse.getEntity();
String body = EntityUtils.toString(httpEntity);
System.out.println("响应体:"+body);
int statusCode = httpResponse.getStatusLine().getStatusCode();
System.out.println("响应码:"+statusCode);
模拟发送post请求
//和get请求基本一致,需要添加入参代码以及对应新增的响应头设置,响应报文获取和上面保持一致
HttpPost post = new HttpPost("测试的接口地址");
//请求头根据需求文档对应添加,举个例子如下设置
post.setHeader("Content-Type", "application/json");
String json = "复制入参json格式的请求报文";
//把json入参放入请求中
post.setEntity(new StringEntity(json,"utf-8"));
HttpClient httpClient = HttpClients.createDefault();
HttpResponse httpResponse = httpClient.execute(post);
本文地址:https://blog.csdn.net/Keep_Learn2020/article/details/109923879
上一篇: 清除svn文件的bat脚本整理
下一篇: 如何进行系统配置