一:创建项目,引入包依赖
我创建的是Java的maven项目,在pom.xml下引入testng和httpclient
httpclient:基于http协议,客户端 HTTP 协议传输类库,用户发送和接受http的消息
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9.9</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
二:封装post和get方法
创建一个工具类RestClient
//get请求方法,不带请求头
public CloseableHttpResponse get(String url) throws ClientProtocolException, IOException {
//创建一个可关闭的HttpClient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
//创建一个httpget对象
HttpGet httpget = new HttpGet(url);
//执行请求,相当于浏览器点击发送按钮,然后赋值给HttpResponse对象接收
CloseableHttpResponse httpResponse = httpclient.execute(httpget);
//返回请求的结果
return httpResponse;
}
//get带请求头
public CloseableHttpResponse get(String url,HashMap<String,String> headermap) throws ClientProtocolException, IOException{
CloseableHttpClient httpclient=HttpClients.createDefault();
HttpGet httpget=new HttpGet(url);
for(Map.Entry<String, String> entry:headermap.entrySet()){
httpget.setHeader(entry.getKey(), entry.getValue());
}
CloseableHttpResponse httpResponse=httpclient.execute(httpget);
return httpResponse;
}
//post方法
public CloseableHttpResponse post(String url,String entityString,HashMap<String,String> headermap) throws ClientProtocolException, IOException{
//创建一个httpClient对象
CloseableHttpClient httpclient=HttpClients.createDefault();
//创建一个httppost对象
HttpPost httppost=new HttpPost(url);
HttpEntity entity=new StringEntity(entityString.toLowerCase());
//设置一个payload
httppost.setEntity(entity);
//加载请求头到httppost对象
if(headermap!=null){
for(Map.Entry<String, String> entry : headermap.entrySet()){
httppost.addHeader(entry.getKey(), entry.getValue());
}
}
//发送请求
CloseableHttpResponse httpResponse = httpclient.execute(httppost);
//返回请求的结果
return httpResponse;
}
三:测试接口
创建一个test执行的类,使用@Test标记
public class DoubanTest {
CloseableHttpResponse closeableHttpResponse;
@Test
public void getMovie() throws IOException {
//接口地址
String url="这是要测试的api";
RestClient rest=new RestClient();
//构造请求头信息
HashMap<String,String> headermap = new HashMap<String,String>();
headermap.put("Content-Type", "application/json");
//构造请求的参数信息
JsonObject json=new JsonObject();
json.addProperty("page", "1");
json.addProperty("count", "2");
json.addProperty("type","video");
//发送post请求
closeableHttpResponse=rest.post(url,json.toString(),headermap);
//获取接口返回状态码
int statusCode=closeableHttpResponse.getStatusLine().getStatusCode();
System.out.println("the code is"+statusCode);
//获取接口的返回内容
String responseString = EntityUtils.toString(closeableHttpResponse.getEntity());
System.out.println("the response is:"+responseString);
}
}
运行test类,在控制台打印出接口相关信息

接口返回打印信息.png
这样最基础的一个接口测试框架算是跑通了