8.1 发送 POST 方法
post 方法和 get 方法是我们在做接口测试时,用的最多的两个请求方法。 在发送请求时它们显著的一个差别就在于,get 方法我们只需要将 url 发送即可,post 我们还需发送一个请求主体;在作用方面,get 方法用于查询,不会改变服务器中的信息;而 Post 方法可用于修改服务器中的信息。
8.1.1 修改 HttpClientUtil 实现发送 POST 请求和获取响应
根据请求的数据是 JSON 对象还是表单形式的键值对,分成了 sendPostByJson 和 sendPostByForm 两类方法,其中 sendPostByForm 方法用 ArrayList 存储 NameValuePair 键值对,再设置请求的主体;sendPostByJson 方法将对象序列化为 JONS 字符串,再设置请求的主体。
public JSONObject sendPostByJson(String url, Object object, HashMap<String, String> headers) throws Exception {
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setConfig(requestConfig);
String json = JSON.toJSONString(object);
StringEntity entity = new StringEntity(json, "utf-8");
entity.setContentType("application/json"); httpPost.setEntity(entity);
if (headers != null) {
// 加载请求头到httppost对象
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity(); String result = null;
if (responseEntity != null) {
result = EntityUtils.toString(responseEntity, "UTF-8");
}
EntityUtils.consume(responseEntity);
JSONObject jsonobj = JSON.parseObject(result);
jsonobj.put(HTTPSTATUS, response.getStatusLine().getStatusCode());
return jsonobj;
} finally {
httpClient.close();
response.close();
}
}
public JSONObject sendPostByForm(String url, Map<String, String> form, HashMap<String, String> headers) throws Exception {
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setConfig(requestConfig);
// 设置请求主体格式
if (form.size() > 0) {
ArrayList<BasicNameValuePair> list = new ArrayList<>();
form.forEach((key, value) -> list.add(new BasicNameValuePair(key, value)));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
}
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
if (headers != null) {
// 设置头部信息
Set<String> set = headers.keySet();
for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
String key = iterator.next();
String value = headers.get(key);
httpPost.setHeader(key, value);
}
}
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
JSONObject jsonobj = JSON.parseObject(result);
jsonobj.put(HTTPSTATUS, response.getStatusLine().getStatusCode());
return jsonobj;
} finally {
httpClient.close(); response.close();
}
}
public JSONObject sendPostByForm(String url, Map<String, String> form)
throws Exception {
return sendPostByForm(url, form, null);
}
public JSONObject sendPostByJson(String url, Object object) throws Exception {
return sendPostByJson(url, object, null);
}
8.2 发送 Put 方法请求和获取响应
Put 方法请求基本上和 sendPostByForm 方法内容一致,只是将 HttpPost 类换做了HttpPut 类。
public JSONObject sendPut(String url, String entityString, HashMap<String, String> headers)throws ClientProtocolException, IOException {
httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
try {
httpPut.setConfig(requestConfig);
httpPut.setEntity(new StringEntity(entityString, "utf-8"));
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPut.setHeader(entry.getKey(), entry.getValue());
}
}
// 发送put请求
response = httpClient.execute(httpPut);
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
JSONObject jsonobj = JSON.parseObject(result);
jsonobj.put(HTTPSTATUS, response.getStatusLine().getStatusCode());
return jsonobj;
} finally {
httpClient.close(); response.close();
}
}
8.3 发送 Delete 方法
Delete 方法更加简单了,它用于删除服务器上的资源,所以执行后只需要返回响应状态码即可。
public int sendDelete(String url) throws ClientProtocolException, IOException {
httpClient = HttpClients.createDefault();
HttpDelete httpDel = new HttpDelete(url);
try {
httpDel.setConfig(requestConfig);
// 发送delete请求
response = httpClient.execute(httpDel);
int statusCode = response.getStatusLine().getStatusCode();
return statusCode;
} finally {
httpClient.close();
response.close();
}
}
8.4 相关源代码
8.4.1 用于给 sendPostByJson 方法传递对象的 User 类:
package com.mytest.httpclient;
public class Uses {
private String name;
private String job;
public User() {
super();
}
public User(String name, String job) {
super();
this.name = name;
this.job = job;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
8.4.2 TestNG 测试类源代码:
package com.mytest.httpclient.test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.mytest.httpclient.HttpClientUtil;
import com.mytest.httpclient.Users;
import com.mytest.httpclient.Util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class RequestMethodTest {
CloseableHttpClient client;
CloseableHttpResponse closeableHttpResponse;
HttpEntity responseBody;
int responseCode;
HttpClientUtil hcu;
String url;
@BeforeTest
public void setUp() {
hcu = new HttpClientUtil ();
}
@Test
public void postByFormTest() throws Exception {
url = "https://reqres.in/api/login";
Map<String,String> params = new HashMap<String,String>();
params.put("email", "eve.holt@reqres.in");
params.put("password", "cityslicka");
JSONObject responseJson = hcu.sendPostByForm(url, params);
// 验证状态码是不是200
int statusCode = responseJson.getInteger(hcu.HTTPSTATUS);
Assert.assertEquals(statusCode, HttpStatus.SC_OK, "status code is not 201");
// 断言响应json内容中name和job是不是期待结果
String token = Util.getValueByJPath(responseJson, "token");
Assert.assertEquals(token, "QpwL5tke4Pnpja7X4", "token is not right");
}
@Test
public void postByJsonTest() throws Exception {
// 对象转换成Json字符串
User user = new User("Anthony", "tester");
url = "https://reqres.in/api/users";
JSONObject responseJson = hcu.sendPostByJson(url, user);
// 验证状态码是不是201
int statusCode = responseJson.getInteger(hcu.HTTPSTATUS);
Assert.assertEquals(statusCode, HttpStatus.SC_CREATED, "status code is not 201");
// 断言响应json内容中name和job是不是期待结果
String name = Util.getValueByJPath(responseJson, "name");
String job = Util.getValueByJPath(responseJson, "job");
Assert.assertEquals(name, "Anthony", "name is not same");
Assert.assertEquals(job, "tester", "job is not same");
}
@Test
public void putTest() throws ClientProtocolException, IOException {
url = "https://reqres.in/api/users/2";
HashMap<String, String> headermap = new HashMap<String, String>();
// 这个在postman 中可以查询到
headermap.put("Content-Type", "application/json");
// 对象转换成Json字符串
Users user = new Users("Anthony", "automation tester");
String userJsonString = JSON.toJSONString(user);
JSONObject responseJson = hcu.sendPut(url, userJsonString, headermap);
// 验证状态码是不是200
int statusCode = responseJson.getInteger(hcu.HTTPSTATUS);
Assert.assertEquals(statusCode, HttpStatus.SC_OK, "response status code is not 200");
// 验证名称为Anthony的jon是不是 automation tester
String jobString = Util.getValueByJPath(responseJson, "job");
Assert.assertEquals(jobString, "automation tester", "job is not same");
}
@Test
public void deleteApiTest() throws ClientProtocolException, IOException
{
url = "https://reqres.in/api/users/2";
int statusCode = hcu.sendDelete(url);
Assert.assertEquals(statusCode, HttpStatus.SC_NO_CONTENT, "status code is not 204");
}
}
————————————————
版权声明:本文为CSDN博主「东方欲晓-」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wd168/article/details/106884459