最近,领了项目的接口测试任务,由于之前一直使用Jmeter工具进行接口的调用,所以一开始并使用Jmeter调用接口进行测试,由于后面的业务比较复杂,在进行某个接口测试的时候需要依赖很多接口,导致维护起来比较费力。于是,尝试对Jmeter工具进行修改,使用Java请求对接口进行封装操作。然后通过Jmeter工具的图形化进行接口测试,效果不错。
由于系统使用HTTPS协议,在进行java脚本编写之前,通过HttpClient对Post、Get、Delete请求协议进行封装在HTTPRequest类中进行调用。
具体步骤如下:
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:
- 创建CloseableHttpClient对象。
- 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
- 如果需要发送请求参数,可可调用setEntity(HttpEntity
entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。 - 调用HttpGet、HttpPost对象的setHeader(String name, String
value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。 - 调用CloseableHttpClient对象的execute(HttpUriRequest
request)发送请求,该方法返回一个CloseableHttpResponse。 - 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String
name)等方法可获取服务器的响应头。 - 释放连接。无论执行方法是否成功,都必须释放连接
具体实现: 1、绕过SSL认证 https利用SSL/TLS建立全信道,加密数据包。HTTPS使用的主要目的是提供对网站服务器的身份认证,同时保护交换数据的隐私与完整性。相对于http协议,Https协议多了一个SSL证书认证。在使用java进行https请求时需要绕过SSL证书。
代码实现如下:
private static CloseableHttpClient getCloseableHttpClient(String httpUrl){
CloseableHttpClient client = null;
if(httpUrl.split(":")[0].equals("https"))
{
try{
SSLContext sslContext;
sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y)->true).build();
RequestConfig config = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build();
client = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y)->true).build();
}catch (Exception e){
e.printStackTrace();
}
}
else if("http".equals(httpUrl.split(":")[0])){
client = HttpClients.createDefault();
}else {
System.out.println("http链接输入错误");
}
return client;
}
2、带token的Get请求 .
public static String httpGet(String httpUrl, String token) {
String result = "";
try {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
client = getCloseableHttpClient(httpUrl);
HttpGet httpGet = new HttpGet(httpUrl);
if (!token.isEmpty()) {
httpGet.setHeader("token", token);
}
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
3、带Json格式的post请求并返回token值和cookie值,用于登录请求 .
public static Map<String ,String > httpPostJsonSetCookie(String httpUrl, String jsonString){
Map<String ,String> map = new HashMap<>();
map.clear();
try{
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try{
client = getCloseableHttpClient(httpUrl);
HttpPost httpPost = new HttpPost(httpUrl);
StringEntity se = new StringEntity(jsonString,"UTF-8");
httpPost.setEntity(se);
httpPost.setHeader(HTTP.CONTENT_TYPE,"application/json");
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
map.put("ResponseResult",EntityUtils.toString(entity));
Header[] headerArray = response.getAllHeaders();
for (Header header:headerArray){
if("Set-Cookie".equals(header.getName())){
map.put("Cookie",header.getValue().split(";")[0]);
break;
}else if("token".equals(header.getName())){
map.put("token",header.getValue().split(";")[0]);
break;
}
else {
continue;
}
}
}finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
}catch (Exception e){
e.printStackTrace();
}
return map;
}
4、带token值得post请求 .
public static String httpPostJson(String httpUrl, String jsonString, String token){
String result = "";
try{
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try{
client = getCloseableHttpClient(httpUrl);
HttpPost httpPost = new HttpPost(httpUrl);
StringEntity se = new StringEntity(jsonString,"UTF-8");
httpPost.setEntity(se);
httpPost.setHeader(HTTP.CONTENT_TYPE,"application/json");
if(!token.isEmpty()) {
httpPost.setHeader("token", token);
}
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
}finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
}catch (Exception e){
e.printStackTrace();
}
return result;
}
5、带token值得Delete请求 .
public static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase{
public static final String METHOD_NAME = "DELETE";
@Override
public String getMethod(){
return METHOD_NAME;
}
public HttpDeleteWithBody(final String httpUrl){
super();
setURI(URI.create(httpUrl));
}
public HttpDeleteWithBody(final URI httpUrl){
super();
setURI(httpUrl);
}
public HttpDeleteWithBody(){
super();
}
}
public static String httpDelete(String httpUrl,String jsonString,String token,String cookie) {
String result = "";
try{
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
client = getCloseableHttpClient(httpUrl);
HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(httpUrl);
httpDelete.setHeader(HTTP.CONTENT_TYPE, "application/json");
if (!token.isEmpty() && !cookie.isEmpty()) {
httpDelete.setHeader("token", token);
httpDelete.setHeader("Cookie", cookie);
}
StringEntity se = new StringEntity(jsonString, "UTF-8");
httpDelete.setEntity(se);
response = client.execute(httpDelete);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} finally {
if (client != null) {
client.close();
}
if (response != null) {
response.close();
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return result;
}
附录:完整代码: 依赖jar包:点击获取
import javax.net.ssl.SSLContext;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
public class HttpRequest {
private static CloseableHttpClient getCloseableHttpClient(String httpUrl){
CloseableHttpClient client = null;
if(httpUrl.split(":")[0].equals("https"))
{
try{
SSLContext sslContext;
sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y)->true).build();
RequestConfig config = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build();
client = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y)->true).build();
}catch (Exception e){
e.printStackTrace();
}
}
else if("http".equals(httpUrl.split(":")[0])){
client = HttpClients.createDefault();
}else {
System.out.println("http链接输入错误");
}
return client;
}
public static String httpGet(String httpUrl, String token) {
String result = "";
try {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
client = getCloseableHttpClient(httpUrl);
HttpGet httpGet = new HttpGet(httpUrl);
if (!token.isEmpty()) {
httpGet.setHeader("token", token);
}
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static String httpGet(String httpUrl,String token,String cookie){
String result = "";
try {
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
client = getCloseableHttpClient(httpUrl);
HttpGet httpGet = new HttpGet(httpUrl);
if (!token.isEmpty()) {
httpGet.setHeader("token", token);
httpGet.setHeader("Cookie", cookie);
}
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} finally {
if (response != null) {
response.close();
}
if (client != null) {
response.close();
}
}
}catch (Exception e){
e.printStackTrace();
}
return result;
}
public static Map<String ,String > httpPostJsonSetCookie(String httpUrl, String jsonString){
Map<String ,String> map = new HashMap<>();
map.clear();
try{
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try{
client = getCloseableHttpClient(httpUrl);
HttpPost httpPost = new HttpPost(httpUrl);
StringEntity se = new StringEntity(jsonString,"UTF-8");
httpPost.setEntity(se);
httpPost.setHeader(HTTP.CONTENT_TYPE,"application/json");
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
map.put("ResponseResult",EntityUtils.toString(entity));
Header[] headerArray = response.getAllHeaders();
for (Header header:headerArray){
if("Set-Cookie".equals(header.getName())){
map.put("Cookie",header.getValue().split(";")[0]);
break;
}else if("token".equals(header.getName())){
map.put("token",header.getValue().split(";")[0]);
break;
}
else {
continue;
}
}
}finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
}catch (Exception e){
e.printStackTrace();
}
return map;
}
public static String httpPostJson(String httpUrl, String jsonString){
String result = "";
try{
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try{
client = getCloseableHttpClient(httpUrl);
HttpPost httpPost = new HttpPost(httpUrl);
StringEntity se = new StringEntity(jsonString,"UTF-8");
httpPost.setEntity(se);
httpPost.setHeader(HTTP.CONTENT_TYPE,"application/json");
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
}finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
}catch (Exception e){
e.printStackTrace();
}
return result;
}
public static String httpPostJson(String httpUrl, String jsonString, String token){
String result = "";
try{
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try{
client = getCloseableHttpClient(httpUrl);
HttpPost httpPost = new HttpPost(httpUrl);
StringEntity se = new StringEntity(jsonString,"UTF-8");
httpPost.setEntity(se);
httpPost.setHeader(HTTP.CONTENT_TYPE,"application/json");
if(!token.isEmpty()) {
httpPost.setHeader("token", token);
}
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
}finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
}catch (Exception e){
e.printStackTrace();
}
return result;
}
public static String httpPostJson(String httpUrl, String jsonString, String token, String cookie){
String result = "";
try{
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try{
client = getCloseableHttpClient(httpUrl);
HttpPost httpPost = new HttpPost(httpUrl);
StringEntity se = new StringEntity(jsonString,"UTF-8");
httpPost.setEntity(se);
httpPost.setHeader(HTTP.CONTENT_TYPE,"application/json");
if(!token.isEmpty() && !cookie.isEmpty()) {
httpPost.setHeader("token", token);
httpPost.setHeader("Cookie", cookie);
}
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
}finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
}catch (Exception e){
e.printStackTrace();
}
return result;
}
public static String httpPostParam(String httpUrl, String token){
String result = "";
try{
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try{
client = getCloseableHttpClient(httpUrl);
HttpPost httpPost = new HttpPost(httpUrl);
if(!token.isEmpty()) {
httpPost.setHeader("token",token);
}
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
}finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
}catch (Exception e){
e.printStackTrace();
}
return result;
}
public static String httpPostParam(String httpUrl, String token,String cookie){
String result = "";
try{
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try{
client = getCloseableHttpClient(httpUrl);
HttpPost httpPost = new HttpPost(httpUrl);
if(!token.isEmpty() && !cookie.isEmpty()) {
httpPost.setHeader("token",token);
httpPost.setHeader("Cookie",cookie);
}
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
}finally {
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
}
}catch (Exception e){
e.printStackTrace();
}
return result;
}
public static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase{
public static final String METHOD_NAME = "DELETE";
@Override
public String getMethod(){
return METHOD_NAME;
}
public HttpDeleteWithBody(final String httpUrl){
super();
setURI(URI.create(httpUrl));
}
public HttpDeleteWithBody(final URI httpUrl){
super();
setURI(httpUrl);
}
public HttpDeleteWithBody(){
super();
}
}
public static String httpDelete(String httpUrl,String jsonString,String token,String cookie) {
String result = "";
try{
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
client = getCloseableHttpClient(httpUrl);
HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(httpUrl);
httpDelete.setHeader(HTTP.CONTENT_TYPE, "application/json");
if (!token.isEmpty() && !cookie.isEmpty()) {
httpDelete.setHeader("token", token);
httpDelete.setHeader("Cookie", cookie);
}
StringEntity se = new StringEntity(jsonString, "UTF-8");
httpDelete.setEntity(se);
response = client.execute(httpDelete);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} finally {
if (client != null) {
client.close();
}
if (response != null) {
response.close();
}
}
}catch(Exception e)
{
e.printStackTrace();
}
return result;
}
}
|