有时候 我们写了接口 需要不断地用 postman 去测试接口 或者用其他的工具去测试 但是都免不了要去手动拼接 url路径
如果GET请求 还要手动输入请求的url 如果是POST请求 还要输入请求体的内容 好麻烦的感觉 因为我们测试和开发都是在
一个项目中 而且好多的pojo都是一样的 还要去手动的粘贴复制 实在是难受
因此 我花费了一个小时写了一个简单的工具类 但是可以实现百分之99的功能
这是第二次更新 采用了Java8的函数式编程来处理检测流程
超级好用
全部使用 建造者模式 一行代码搞定测试
@Test
public void TestMapCount(){
// fun是一个函数对象 写好你要检测的流程
API.ME(HOST.LOCAL).fixHead("loginId:2").addBasUrl("/selectMapParasByGroupId2").fun((j)->{
JSONArray data = j.getJSONArray("data");
System.out.println(data.size());
}).GET();
}
// 这是一个固定的Token 当我们测试的时候 如果需要验证 可以加上一个固定的请求头
HashMap<String,Object> token = new HashMap<>();
token.put("Token","hello world");
API.ME().fixHead(token) // 添加固定的请求头
// person 对象是我们写好的pojo对象
// 如果是用postMan 测试 去要手动粘贴name和age’的键值对上去 太麻烦
// 现在我们生成一个要测试的对象 如果要把对象的属性值添加进请求Body里面 就去设置哦
// 如果不设置 就不会去添加入请求体 很方便
Person person = new Person("lixin",134);
// addBaseUrl 就是去添加要请求的url
API.ME().addBasUrl("/test").addBasUrl("/addPerson").packReqBody(person).POST();
// 如果需要添加一个pojo没有的属性值 怎么办?
HashMap<String,Object> map = new HashMap<>();
map.put("name","lixin");
map.put("age",13);
API.ME().fixHead(token).addBasUrl("/test").addBasUrl("/addPerson").packReqBody(map).POST();
// 也可以去添加一个HashMap进去
源码在下面 就一百来行 使用的时候 粘贴进项目就行了
全局采用构建者设计模式 可以连写 但是以下的次序尽量不要乱
fixHead // 添加固定的请求头
addBasUrl //添加基本的Url 就是在?号之前的
addReqUrl //添加请求的url 用于get请求 就是url的?号之后的 , 参数可以是对象 或者 map 传入即可 其他的不用操心
packReqBody //参数可以是map也可以是对象 用来拼接请求体
GET/POST //最后用来发送请求
public class API {
// 类型支持
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// 请求客户端
OkHttpClient client ;
//
Request.Builder builder;
StringBuilder basicUrl ;
StringBuilder urlRequst ;
HashMap<String,Object> postBody;
BiFunction fun1;
Consumer<JSONObject> fun2;
public static API ME(){
return new API();
}
public static API ME(HOST host){
API api = new API();
api.basicUrl = new StringBuilder(host.getName());
return api;
}
public API() {
client = new OkHttpClient();
builder = new Request.Builder();
urlRequst = new StringBuilder("");
postBody = new HashMap<>();
}
/**
* 加入固定请求头
* @param map 请求头
*/
public API fixHead(HashMap<String,Object> map){
for (Map.Entry<String,Object> entry : map.entrySet()){
builder.addHeader(entry.getKey(), entry.getValue().toString());
}
return this;
}
public API fixHead(String... strings){
for (String s : strings){
String[] split = s.split(":");
builder.addHeader(split[0],split[1]);
}
return this;
}
// 添加requstURL
public API addReqUrl (Object object) {
if (object instanceof HashMap){
HashMap<String,Object> maps = (HashMap<String, Object>) object;
for (Map.Entry<String,Object> entry: maps.entrySet()) {
urlRequst.append(entry.getKey());
urlRequst.append("=");
urlRequst.append(entry.getValue().toString());
urlRequst.append("&");
}
return this;
}
// 获取所有的feild
Field[] declaredFields = object.getClass().getDeclaredFields();
// 组装url
try {
for (Field field : declaredFields){
field.setAccessible(true);
if(field.get(object)==null){
continue;
}
urlRequst.append(field.getName());
urlRequst.append("=");
urlRequst.append(field.get(object).toString());
urlRequst.append("&");
}
}catch (Exception e){}
return this;
};
public API addReqUrl(String... strings){
for (String string : strings) {
String[] split = string.split(":");
urlRequst.append(split[0]);
urlRequst.append("=");
urlRequst.append(split[1]);
urlRequst.append("&");
}
return this;
}
// 添加basic的URL路径
public API addBasUrl (String url){
basicUrl.append(url);
return this;
}
// 发送GET请求
public void GET(){
StringBuilder getUrl = basicUrl;
//去除urlRequest的尾部空格
if(!"".equals(urlRequst.toString())){
getUrl.append("?");
urlRequst.deleteCharAt(urlRequst.lastIndexOf("&"));
getUrl.append(urlRequst);
}
System.out.println("GET ===>"+getUrl.toString());
Request request = builder.url(getUrl.toString()).build();
Call call = client.newCall(request);
try {
Response response = call.execute();
com.alibaba.fastjson.JSONObject parse = com.alibaba.fastjson.JSON.parseObject(response.body().string());
fun2.accept(parse);
} catch (IOException e) {
e.printStackTrace();
}
}
// 发送GET请求
public void GET(HOST host){
StringBuilder getUrl = new StringBuilder(host.getName());
if(!"".equals(urlRequst.toString())){
getUrl.append("?");
urlRequst.deleteCharAt(urlRequst.lastIndexOf("&"));
getUrl.append(urlRequst);
}
System.out.println("GET =====>"+getUrl.toString());
Request request = builder.url(getUrl.toString()).build();
Call call = client.newCall(request);
try {
Response response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
// 添加请求的body
public API packReqBody(Object object){
if (object instanceof HashMap){
HashMap<String,Object> maps = (HashMap<String, Object>) object;
postBody.putAll(maps);
return this;
}
Field[] declaredFields = object.getClass().getDeclaredFields();
try {
for (Field field : declaredFields){
field.setAccessible(true);
if(field.get(object)==null||"".equals(field.get(object))){
continue;
}
postBody.put(field.getName(),field.get(object).toString());
}
}catch (Exception e){}
return this;
}
// 发送POST
public void POST(){
RequestBody body = RequestBody.create(JSON, com.alibaba.fastjson.JSON.toJSONBytes(postBody));
// 将basicUrl与urlRequest结合起来
Request request = builder.url(basicUrl.append(urlRequst).toString()).post(body).build();
System.out.println(basicUrl.toString());
try {
Response execute = client.newCall(request).execute();
com.alibaba.fastjson.JSONObject parse = com.alibaba.fastjson.JSON.parseObject(execute.body().string());
fun2.accept(parse);
} catch (IOException e) {
System.out.println("POST 失败");
e.printStackTrace();
}
}
// 加入处理函数
public API fun(BiFunction function){
this.fun1 = function;
return this;
}
public API fun(Consumer<com.alibaba.fastjson.JSONObject> consumer){
this.fun2 = consumer;
return this;
}
}
``
public enum HOST {
LOCAL(“http://localhost:8080/hyjj_back_war_exploded”),
ROMOTE(“http://xxxxxxx:9092/hyjj_back”);
String name;
HOST(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190916095300758.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwNTkyNDg0,size_16,color_FFFFFF,t_70)