做接口测试时,Http接口是最常见的一种接口类型,我们经常需要基于HttpClient包去发送get/post请求对Http接口进行测试。
1.HttpClient的maven配置:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
2.通过HttpClient发送get请求:
public static String doGet(String uri, HashMap<String, String> headerMap) throws Exception {
HttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(new URI(uri));
// set header
if (null != headerMap && headerMap.size() > 0) {
for (String key : headerMap.keySet()) {
request.setHeader(key, headerMap.get(key));
}
}
HttpResponse response = client.execute(request);
// 这里可以通过statusCode进行一些判断
// response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String res = "";
if (entity != null) {
res = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
}
return res;
}
public String getWeatherCities() {
String res = "";
try {
res = HttpService.doGet("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity?byProvinceName=江苏");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(res);
return res;
}
执行getWeatherCities(),打印返回值:
3.通过HttpClient发送Post请求,带参数
/**
* @return
*/
public static String doPost(String uri, HashMap<String, String> params, HashMap<String, String> headerMap) throws Exception {
HttpClient client = HttpClients.createDefault();
HttpPost request = new HttpPost(new URI(uri));
// set header
if (null != headerMap && headerMap.size() > 0) {
for (String key : headerMap.keySet()) {
request.setHeader(key, headerMap.get(key));
}
}
// set entity
if (null != params && params.size() > 0) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
NameValuePair pair = new BasicNameValuePair(key, params.get(key));
pairs.add(pair);
}
HttpEntity entity = new UrlEncodedFormEntity(pairs, "utf-8");
request.setEntity(entity);
}
HttpResponse response = client.execute(request);
// 这里可以通过statusCode进行一些判断
// response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String res = "";
if (entity != null) {
res = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);
}
return res;
}
public String postWeatherCities() {
String res = "";
HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("byProvinceName", "江苏");
try {
res = HttpService.doPost("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getSupportCity", paramMap, null);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(res);
return res;
}
执行postWeatherCities,正确打印返回值:
总结下:
1、首先创建HttpClient对象
2、创建HttpGet/HttpPost对象,并设置header和entity,其中Post方法通过entity传入参数
3、HttpClient对象调用execute方法,传入HttpGet/HttpPost对象
4、返回HttpResponse对象,对entity的值进行处理获取返回值内容