自动化测试系列(7)—— 模拟post/get请求进行接口测试
模拟post/get请求进行接口测试跟selenium没有关系,主要用到了OkHttp来对网页进行模拟post/get请求,和利用testng接收测试案例和显示测试结果
本项目对网页请求的操作主要用了okhttp3,首先在pom.xml文件下写上引入okhttp3的jar包的代码并导入
<!--okhttp3 jar-->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
</dependency>
OkHttpUtil工具类代码参考了……emmmmmm,这代码辗转了几个项目几台电脑,忘记在哪看的了,算了直接贴吧,知道的小伙伴可以留言告诉我一下。
OkhttpUtil工具类代码
public class OkHttpUtil {
private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
/**
* get
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @return
*/
public static String get(String url, Map<String, String> queries) {
String responseBody = "";
StringBuffer sb = new StringBuffer(url);
if (queries != null && queries.keySet().size() > 0) {
boolean firstFlag = true;
Iterator iterator = queries.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry<String, String>) iterator.next();
if (firstFlag) {
sb.append("?" + entry.getKey() + "=" + entry.getValue());
firstFlag = false;
} else {
sb.append("&" + entry.getKey() + "=" + entry.getValue());
}
}
}
Request request = new Request.Builder()
.url(sb.toString())
.build();
Response response = null;
try {
OkHttpClient okHttpClient = new OkHttpClient();
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp3 put error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* post
*
* @param url 请求的url
* @param params post form 提交的参数
* @return
*/
public static String post(String url, Map<String, String> params) {
String responseBody = "";
FormBody.Builder builder = new FormBody.Builder();
//添加参数
if (params != null && params.keySet().size() > 0) {
int count = 1;
for (String key : params.keySet()) {
if(params.get(key) != null)builder.add(key, params.get(key));
count++;
}
}
Request request = new Request.Builder()
.url(url)
.post(builder.build())
.build();
Response response = null;
try {
OkHttpClient okHttpClient = new OkHttpClient();
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (response.isSuccessful()) {
System.out.println("success:"+url);
return response.body().string();
}
System.out.println("fail:"+url);
} catch (Exception e) {
logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* get
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @return
*/
public static String getForHeader(String url, Map<String, String> queries) {
String responseBody = "";
StringBuffer sb = new StringBuffer(url);
if (queries != null && queries.keySet().size() > 0) {
boolean firstFlag = true;
Iterator iterator = queries.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = (Map.Entry<String, String>) iterator.next();
if (firstFlag) {
sb.append("?" + entry.getKey() + "=" + entry.getValue());
firstFlag = false;
} else {
sb.append("&" + entry.getKey() + "=" + entry.getValue());
}
}
}
Request request = new Request.Builder()
.addHeader("key", "value")
.url(sb.toString())
.build();
Response response = null;
try {
OkHttpClient okHttpClient = new OkHttpClient();
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp3 put error >> ex = {}", e.getMessage());
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
* 参数一:请求Url
* 参数二:请求的JSON
* 参数三:请求回调
*/
public static String postJsonParams(String url, String jsonParams) {
String responseBody = "";
okhttp3.RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = null;
try {
OkHttpClient okHttpClient = new OkHttpClient();
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
/**
* Post请求发送xml数据....
* 参数一:请求Url
* 参数二:请求的xmlString
* 参数三:请求回调
*/
public static String postXmlParams(String url, String xml) {
String responseBody = "";
RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = null;
try {
OkHttpClient okHttpClient = new OkHttpClient();
response = okHttpClient.newCall(request).execute();
int status = response.code();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
} finally {
if (response != null) {
response.close();
}
}
return responseBody;
}
}
调用OkHttpUtil的postJsonParams方法模拟post请求
@Test(dataProvider = "list")
public void action(LoanerLoginVo loanerUpdateBasicInfoVo) {
JSONObject jsonObject = JSONObject.fromObject(loanerUpdateBasicInfoVo);
String url = "http://localhost/huinongloan2/web/loaner/loanerLogin";
String res = OkHttpUtil.postJsonParams(url, String.valueOf(jsonObject));
//System.out.println(res);
JSONObject jsonObjectRes = JSONObject.fromObject(res);
if (jsonObjectRes.get("code")==1) {
throw new RuntimeException(jsonObjectRes.get("errmsg").toString());
} else {
Reporter.log(DateUtils.getCurrentTime() + ": 验证成功");
}
}
有问题请留言。