一、什么是接口

接口是前端和后端的数据通道

二、如何获取接口

1.开发不提供接口文档,通过抓包工具比如fiddler进行抓取,如下:

步骤一:设置浏览器(比如火狐)代理

java接口测试入门-LMLPHP

java接口测试入门-LMLPHP

步骤二:设置url过滤器,进入包的过滤抓取

java接口测试入门-LMLPHP

步骤三:查看fiddler抓取的包,获取到接口

java接口测试入门-LMLPHP

2.开发提供详细接口文档

三、通过Java代码模拟客户端向服务器发送请求,查看接口响应

步骤一:下载开源对象HttpClient所属的Jar包至本地,下载地址:http://hc.apache.org/downloads.cgi

步骤二:将解压后lib目录下的jar文件拷贝至java工程并build path

java接口测试入门-LMLPHP

java接口测试入门-LMLPHP

步骤三:创建Java类,编写代码模拟客户端发送请求,查看响应

a)get请求

     private static void get() throws IOException, ClientProtocolException {
String url = "http://xxx.com//loginValidate.do";
url += "?userName=xxx&password=xxx";
//客户端
HttpClient client = HttpClients.createDefault();
//建立get请求
HttpGet get = new HttpGet(url);
//发送请求,得到响应
HttpResponse response = client.execute(get);
//返回响应体
HttpEntity entity = response.getEntity();
//将响应体以字符串形式返回
String content = EntityUtils.toString(entity);
System.out.println((content));
}

b) post请求

 private static void post() throws UnsupportedEncodingException, IOException, ClientProtocolException {
String url = "http://xxxx.com//loginValidate.do";
//客户端
HttpClient client = HttpClients.createDefault();
//建立post请求
HttpPost post = new HttpPost(url);
//封装参数信息,使用list保存
List<NameValuePair> pairs = new ArrayList();
NameValuePair pair1 = new BasicNameValuePair("userName", "xxxx");
NameValuePair pair2 = new BasicNameValuePair("password","xxxx");
pairs.add(pair1);
pairs.add(pair2);
post.setEntity(new UrlEncodedFormEntity(pairs)); //发送请求,得到响应
HttpResponse response = client.execute(post);
//返回响应体
HttpEntity entity = response.getEntity();
//将响应体以字符串形式返回
String content = EntityUtils.toString(entity);
System.out.println((content));
}
04-26 19:08
查看更多