一、Har文件获取
- 在Web端,使用Chrome浏览器,打开开发者工具(F12),我们可以对浏览器的行为进行抓包
- 选中接口右击,选择
Copy all as HAR
,这样就可以把接口的内容全部都以HAR的形式复制了下来
二、HAR reader
- 将复制好的内容保存至以.json文件结尾的文本中,我们可以看到其实内容格式就是一种json格式,只不过有它定义好的格式规范
在entries-object-request下有接口的method、url、queryString、postData(body)等完整的请求信息
- 在GitHub上有人提供了har的操作工具:https://github.com/sdstoehr/har-reader
- 其中介绍了各种读取操作har的方法示例和源码,可供学习查阅:
- https://github.com/sdstoehr/har-reader/tree/ad1674bf86c1ba9e7e1b7cbc90cfaa35c3b4f639/src/test/java/de/sstoehr/harreader/model
- 获取数据方式也很简单,整体都是以json的层次,用get+字段key来获取对应json字段的value
三、操作演示
- 首先导入依赖
<dependency>
<groupId>de.sstoehr</groupId>
<artifactId>har-reader</artifactId>
<version>2.1.4</version>
</dependency>
- 建立一个Restful类用来保存接口数据对象
import java.util.HashMap;
public class Restful {
public String url;
public String method;
public HashMap<String, Object> header = new HashMap<>();
public HashMap<String, Object> query = new HashMap<>();
public String body;
}
- 读取har文件,获取文件路径
HarReader harReader = new HarReader();
try {
//读取har文件,获取文件路径,对路径进行编码设置
Har har = harReader.readFromFile(new File(URLDecoder.decode(getClass().getResource(harJsonPath).getPath(), "utf-8")));
}
- 遍历entries,正则匹配到包含API信息的object(因为有的接口har中会有多个object,只有一个是我们需要的)
HarRequest harRequest = new HarRequest();
//遍历entries,正则匹配到包含API信息的object
Boolean match = false;
for (HarEntry entry : har.getLog().getEntries()){
harRequest= entry.getRequest();
if (harRequest.getUrl().matches(urlPattern)){
match = true;
break;
}
}
if (match == false){
throw new Exception("【ERROR】未找到正确的URL");
}
- 去除URL中?后面的内容,获取url
if (harRequest.getUrl().contains("?")){
restful.url = harRequest.getUrl().split("\\?")[0];
}else {
restful.url = harRequest.getUrl();
}
- 获取method、queryString、postData(body)
harRequest.getQueryString().forEach(q->{
restful.query.put(q.getName(),q.getValue());
});
restful.method = harRequest.getMethod().toString();
restful.body = harRequest.getPostData().getText();
- 完整方法代码
public Restful getApiFromHar(String harJsonPath ,String urlPattern){
HarReader harReader = new HarReader();
Restful restful = new Restful();
try {
//读取har文件,获取文件路径,对路径进行编码设置
Har har = harReader.readFromFile(new File(URLDecoder.decode(getClass().getResource(harJsonPath).getPath(), "utf-8")));
HarRequest harRequest = new HarRequest();
//遍历entries,正则匹配到包含API信息的object
Boolean match = false;
for (HarEntry entry : har.getLog().getEntries()){
harRequest= entry.getRequest();
if (harRequest.getUrl().matches(urlPattern)){
match = true;
break;
}
}
if (match == false){
throw new Exception("【ERROR】未找到正确的URL");
}
if (harRequest.getUrl().contains("?")){
restful.url = harRequest.getUrl().split("\\?")[0];
}else {
restful.url = harRequest.getUrl();
}
harRequest.getQueryString().forEach(q->{
restful.query.put(q.getName(),q.getValue());
});
restful.method = harRequest.getMethod().toString();
restful.body = harRequest.getPostData().getText();
return restful;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
最后
这样我们就可以借助浏览器抓包生成har文件,很容易的获取api的信息,用来进行接口自动化的测试工作了~