package com.test.client;
import java.io.IOException;
import java.util.HashMap;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class TestGetApi {
public static void main(String[] args) throws ClientProtocolException, IOException {
//接口地址&登陆信息&参数
String url = "";//被测的API地址
//声明变量
CloseableHttpClient httpclient;//实例化一个可以关闭流释放流相关资源的httpclient对象;抽象类不可直接实例化其本身
HttpGet httpGet;
CloseableHttpResponse httpResponse;
HttpEntity responseBody;
int responseCode;
Header[] responseHeader;
httpclient = HttpClients.createDefault();//创建httpclient实例,httpclient是一个传输库,用于在客户端发送和接受http消息
httpGet = new HttpGet(url);//实例化请求post/get等诸多
httpGet.addHeader("Cookie", "Cookie");//被测接口需要Cookie,才可以请求通
httpResponse = httpclient.execute(httpGet);//httplient发送get类型的请求,执行成功,得到响应返回值
responseCode = httpResponse.getStatusLine().getStatusCode();//获取返回值状态
responseBody = httpResponse.getEntity();//获取返回值body
responseHeader = httpResponse.getAllHeaders();//获取返回值header信息
//因为返回的Entity看不懂,需要用工具类tostring一下,就是正常的body了。
String responseBodyString = EntityUtils.toString(responseBody, "utf-8");
//header:[Lorg.apache.http.Header;@4a9789ee,所以使用hashmap将header信息以键值对形式展示出来,
HashMap<String, String> hashmap=new HashMap<String, String>();
for(Header header:responseHeader) {
hashmap.put(header.getName(), header.getValue());
}
System.out.println(responseCode);
System.out.println(responseBodyString);
System.out.println(hashmap);
}
}
API自动化测试一(eclipse+maven+java+Httpclinet)
最新推荐文章于 2023-10-31 14:20:59 发布