后面我们需要设计测试用例并执行post请求,因此需要对上一篇的post的请求进行封装,允许不同参数的用例能够执行此方法
将Java接口自动化测试(二) 的内容做以修改:
1、首先post的请求我们接收的参数是一个map类型参数
2、返回值类型是一个JSON类型
3、根据具体的需求设计参数和返回值类型,具体post请求执行的过程都是一样的
package com.test.httpclient;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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 java.io.IOException;
import java.util.Map;
public class HttpClientPost {
//POST登录方法
public JSONObject LoginPost(Map<String, Object> map) throws IOException
{
//创建一个获取连接客户端的工具
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建Post请求
HttpPost httpPost = new HttpPost("http://localhost:8081/api/login");
//添加请求头
httpPost.addHeader("Content-Type","application/json;charset=UTF-8");
//封装请求参数,将map集合转换成json格式
JSONObject jsonString = new JSONObject(map);
//使用StringEntity转换成实体类型
StringEntity entity = new StringEntity(jsonString.toString(),"UTF-8");
//将封装的参数添加到Post请求中
httpPost.setEntity(entity);
//执行请求
CloseableHttpResponse response = httpClient.execute(httpPost);
//获取响应的实体
HttpEntity responseEntity = response.getEntity();
//转化成字符串
String entityString = EntityUtils.toString(responseEntity);
//转换成JSON格式输出
JSONObject result = JSONObject.parseObject(entityString);
response.close();
httpClient.close();
return result;
}
}