HttpClient是一个实现了http协议的客户端接口调用的技术,可以通过他来模拟测试工具发出接口请求,完成接口调用。
1.集成eclipse(maven)项目的依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
2.接口调用步骤
//指定接口地址的是请求地址
//指定接口的请求方式:post
//准备测试数据
//在post请求中将测试数据注入
//发起请求,获取接口响应信息(状态码,响应报文等)
//相当于发送按钮
//获取响应结果
//获取响应结果的状态码
//获取响应结果的报文体
public static void main(String[] args) throws ClientProtocolException, IOException {
//指定接口地址的是请求地址
String url="http:#####";
//指定接口的请求方式:post
HttpPost post=new HttpPost(url);
//准备测试数据
String mobilephone="1312##";
String pwd="123456";
List<BasicNameValuePair> parameters=new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("mobilephone", mobilephone));
parameters.add(new BasicNameValuePair("pwd", pwd));
HttpEntity entity=new UrlEncodedFormEntity(parameters,"utf-8");
//在post请求中将测试数据注入
post.setEntity(entity);
//发起请求,获取接口响应信息(状态码,响应报文等)
//相当于发送按钮
HttpClient client=HttpClients.createDefault();
//获取响应结果
HttpResponse response=client.execute(post);
//获取响应结果的状态码
int code=response.getStatusLine().getStatusCode();
//获取响应结果的报文体
String result=EntityUtils.toString(response.getEntity());
System.out.println(code);
System.out.println(result);
public class GetDemo {
public static void main(String[] args) throws ClientProtocolException, IOException {
//准备接口地址
String url="http:/######";
//准备测试数据
String mobilephone="131####";
String pwd="123456";
//url拼接
url+="?"+mobilephone+"&"+pwd;
//指定接口的请求方式
HttpGet httpGet=new HttpGet(url);
//发起请求
HttpClient client=HttpClients.createDefault();
//请求返回值需要用发起的请求的execute方法
HttpResponse response=client.execute(httpGet);
//响应数据的状态码
int code=response.getStatusLine().getStatusCode();
//响应数据的报文体
String result=EntityUtils.toString(response.getEntity());
System.out.println(code);
System.out.println(result);
}