接口测试 用 okhttp3 来写接口测试脚本,cookie 怎么弄?

围城 · January 09, 2017 · Last by 其实我是一个QA replied at January 09, 2017 · 1229 hits

这是封装的请求方法

import net.sf.json.JSONObject;
import okhttp3.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

class TestMethod {
private static String baseUrl = "xxxxxxx.com";
//post请求
static JSONObject doPost(String url, String json) throws IOException {
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(baseUrl + url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return JSONObject.fromObject(response.body().string());
}
}
//get请求
static JSONObject doGet(String url, HashMap<String, String> param) throws IOException {
if (param != null) {
Iterator<String> it = param.keySet().iterator();
StringBuffer sb = null;
while (it.hasNext()) {
String key = it.next();
String value = param.get(key);
if (sb == null) {
sb = new StringBuffer();
sb.append("?");
} else {
sb.append("&");
}
sb.append(key);
sb.append("=");
sb.append(value);
}
url += sb.toString();
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(baseUrl + url)
.get()
.build();
try (Response response = client.newCall(request).execute()) {
return JSONObject.fromObject(response.body().string());
}
}
//put请求
static JSONObject doPut(String url, String json) throws IOException {
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(baseUrl + url)
.put(body)
.build();
try (Response response = client.newCall(request).execute()) {
return JSONObject.fromObject(response.body().string());
}
}
//delete请求
static JSONObject doDelete(String url, String json) throws IOException {
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(baseUrl + url)
.delete(body)
.build();
try (Response response = client.newCall(request).execute()) {
return JSONObject.fromObject(response.body().string());
}
}
}

这是操作退出接口

import net.sf.json.JSONObject;
import java.io.IOException;

public class LogoutTest {
private static String logoutUrl = "/api/v1/logout";
//成功退出
public static JSONObject logoutSuccess() throws IOException {
return TestMethod.doGet(logoutUrl, null);
}
//无cookie退出
public static JSONObject logoutFail() throws IOException {
return TestMethod.doGet(logoutUrl, null);
}
}

所以想问下,cookie或者session怎么处理好?

共收到 1 条回复 时间 点赞

用rest-assured框架吧。

需要 Sign In 后方可回复, 如果你还没有账号请点击这里 Sign Up