目录
1.HttpClient作用
模拟客户端发送请求
2.测试框架搭建
(1)JDK环境
网上有很多
(2)TestNG引入
(3)HttpClient引入
在maven项目的pom.xml中引入如下两个依赖
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
3.发送Get请求和post请求
如果post提交的是json类型数据,需要在pom.xml中添加依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
get请求:
// 准备url
String url="http://www.baidu.com";
//请求方法
HttpGet get = new HttpGet(url);
//请求头
get.setHeader("Authorization",tokenV);
//准备一个发送请求的客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 发送请求得到响应报文-java中封装为对象
CloseableHttpResponse response = httpClient.execute(get);
post请求
String url="http://www.baidu.com";
HttpPost post=new HttpPost(url);
//添加请求头
post.setHeader("Content-Type","application/json");
//准备post参数
// -- 1-json类型
JSONObject json = new JSONObject();
json.put("username","admin");
json.put("password","123456");
System.out.println("请求参数:"+json);
// 发送 json 类型数据,通过new StringEntity(),可将Content-Type设置为text/plain类型
post.setEntity(new StringEntity(json.toString(),"UTF-8"));
//创建发请求的客户端
CloseableHttpClient httpClient=HttpClients.createDefault();
//获得响应内容
CloseableHttpResponse response=httpClient.execute(post);
实际项目展示
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
/**
* @author zhaomin
* @date 2023/4/6 16:34
*/
public class CategoriesTest {
//URL会变、参数会变、请求头会变
// @BeforeMethod
@Test(dependsOnMethods = {
"getToken"})
public void getCategories() throws ClientProtocolException, IOException {
// 请求Url
String url = "http://127.0.0.1:8888/api/private/v1/categories?type=1";
Single token=Single.INSTANCE;
String tokenV=token.getValue();
// 请求方法
HttpGet get = new HttpGet(url);
get.setHeader("Authorization",tokenV);
// 准备一个发送请求的客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 发送请求得到响应报文-java中封装为对象
CloseableHttpResponse response = httpClient.execute(get);
//状态行
StatusLine statusLine = response.getStatusLine();
// 加断言-- todo
System.out.println(statusLine.getReasonPhrase());
System.out.println(statusLine.getStatusCode());
System.out.println(statusLine.getProtocolVersion());
// 响应头
Header[] headers = response.getAllHeaders();
for (Header item : headers
) {
System.out.println(item);
}
// 响应体
HttpEntity entity = response.getEntity();
String entityString = EntityUtils.toString(entity);
// 加断言-- todo
// System.out.println(entity);
System.out.println(entityString);
}
@Test
public void getToken() throws ClientProtocolException, IOException {
String url="http://127.0.0.1:8888/api/private/v1/login";
HttpPost post=new HttpPost(url);
//添加请求头
post.setHeader("Content-Type","application/json");
// post.setHeader("Content-Length","3843");
//准备post参数
// -- 1-json类型
JSONObject json = new JSONObject();
json.put("username","admin");
json.put("password","123456");
System.out.println("请求参数:"+json);
// 发送 json 类型数据,通过new StringEntity(),可将Content-Type设置为text/plain类型
post.setEntity(new StringEntity(json.toString(),"UTF-8"));
//--2-准备普通类型参数
/*
List<NameValuePair> parameters=new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username","admin"));
parameters.add(new BasicNameValuePair("password","123456"));
HttpEntity requestEntity=new UrlEncodedFormEntity(parameters);
post.setEntity(requestEntity);
*/
//创建发请求的客户端
CloseableHttpClient httpClient=HttpClients.createDefault();
//获得响应内容
CloseableHttpResponse response=httpClient.execute(post);
StatusLine statusLine = response.getStatusLine();
HttpEntity entity=response.getEntity();
System.out.println(entity);
String entityString=EntityUtils.toString(entity);
JSONObject jsonObj=JSONObject.parseObject(entityString);
String status=jsonObj.getJSONObject("meta").getString("status");
Assert.assertEquals("200",status,"获取token失败");
String tokenV=jsonObj.getJSONObject("data").getString("token");
// entityString.en
Single token=Single.INSTANCE;
token.setKey("token");
token.setValue(tokenV);
System.out.println(token.getKey());
System.out.println(entityString);
}
}
4.发送post请求
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
/**
* @author zhaomin
* @date 2023/4/6 16:34
*/
public class CategoriesTest {
//URL会变、参数会变、请求头会变
// @BeforeMethod
@Test(dependsOnMethods = {
"getToken"})
public void getCategories() throws ClientProtocolException, IOException {
// 请求Url
String url = "http://127.0.0.1:8888/api/private/v1/categories?type=1";
Single token=Single.INSTANCE;
String tokenV=token.getValue();
// 请求方法
HttpGet get = new HttpGet(url);
get.setHeader("Authorization",tokenV);
// 准备一个发送请求的客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 发送请求得到响应报文-java中封装为对象
CloseableHttpResponse response = httpClient.execute(get);
//状态行
StatusLine statusLine = response.getStatusLine();
// 加断言-- todo
System.out.println(statusLine.getReasonPhrase());
System.out.println(statusLine.getStatusCode());
System.out.println(statusLine.getProtocolVersion());
// 响应头
Header[] headers = response.getAllHeaders();
for (Header item : headers
) {
System.out.println(item);
}
// 响应体
HttpEntity entity = response.getEntity();
String entityString = EntityUtils.toString(entity);
// 加断言-- todo
// System.out.println(entity);
System.out.println(entityString);
}
@Test
public void getToken() throws ClientProtocolException, IOException {
String url="http://127.0.0.1:8888/api/private/v1/login";
HttpPost post=new HttpPost(url);
//添加请求头
post.setHeader("Content-Type","application/json");
// post.setHeader("Content-Length","3843");
//准备post参数
// -- 1-json类型
JSONObject json = new JSONObject();
json.put("username","admin");
json.put("password","123456");
System.out.println("请求参数:"+json);
// 发送 json 类型数据,通过new StringEntity(),可将Content-Type设置为text/plain类型
post.setEntity(new StringEntity(json.toString(),"UTF-8"));
//--2-准备普通类型参数
/*
List<NameValuePair> parameters=new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username","admin"));
parameters.add(new BasicNameValuePair("password","123456"));
HttpEntity requestEntity=new UrlEncodedFormEntity(parameters);
post.setEntity(requestEntity);
*/
//创建发请求的客户端
CloseableHttpClient httpClient=HttpClients.createDefault();
//获得响应内容
CloseableHttpResponse response=httpClient.execute(post);
StatusLine statusLine = response.getStatusLine();
HttpEntity entity=response.getEntity();
System.out.println(entity);
String entityString=EntityUtils.toString(entity);
JSONObject jsonObj=JSONObject.parseObject(entityString);
String status=jsonObj.getJSONObject("meta").getString("status");
Assert.assertEquals("200",status,"获取token失败");
String tokenV=jsonObj.getJSONObject("data").getString("token");
// entityString.en
Single token=Single.INSTANCE;
token.setKey("token");
token.setValue(tokenV);
System.out.println(token.getKey());
System.out.println(entityString);
}
}
post请求封装
如果有多个post请求时,不用每次都写重复。
@Test
public String post(String url, HashMap<String,String> paramsMap)throws ClientProtocolException, IOException{
HttpPost post=new HttpPost(url);
//参数
Set<String> keySet=paramsMap.keySet();
JSONObject json = new JSONObject();
for(String item:keySet){
json.put(item,paramsMap.get(item));
}
// 发送 json 类型数据,通过new StringEntity(),可将Content-Type设置为text/plain类型
post.setEntity(new StringEntity(json.toString(),"UTF-8"));
CloseableHttpClient httpClient=HttpClients.createDefault();
CloseableHttpResponse response=httpClient.execute(post);
HttpEntity entity=response.getEntity();
String entityString = EntityUtils.toString(entity);
return entityString;
}