基于http协议的自定义协议封装

最近,领了项目的接口测试任务,由于之前一直使用Jmeter工具进行接口的调用,所以一开始并使用Jmeter调用接口进行测试,由于后面的业务比较复杂,在进行某个接口测试的时候需要依赖很多接口,导致维护起来比较费力。于是,尝试对Jmeter工具进行修改,使用Java请求对接口进行封装操作。然后通过Jmeter工具的图形化进行接口测试,效果不错。

由于系统使用HTTPS协议,在进行java脚本编写之前,通过HttpClient对Post、Get、Delete请求协议进行封装在HTTPRequest类中进行调用。

具体步骤如下:

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:

  1. 创建CloseableHttpClient对象。
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  3. 如果需要发送请求参数,可可调用setEntity(HttpEntity
    entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。
  4. 调用HttpGet、HttpPost对象的setHeader(String name, String
    value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
  5. 调用CloseableHttpClient对象的execute(HttpUriRequest
    request)发送请求,该方法返回一个CloseableHttpResponse。
  6. 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String
    name)等方法可获取服务器的响应头。
  7. 释放连接。无论执行方法是否成功,都必须释放连接

具体实现:
1、绕过SSL认证
https利用SSL/TLS建立全信道,加密数据包。HTTPS使用的主要目的是提供对网站服务器的身份认证,同时保护交换数据的隐私与完整性。相对于http协议,Https协议多了一个SSL证书认证。在使用java进行https请求时需要绕过SSL证书。

代码实现如下:

 /**
     * 绕过验证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请求.

/**
     *  带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值,用于登录请求.

 /**
     * 带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请求.

/**
     * 带Json格式参数传入post方法
     * 带token和不带cookie
     */
    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请求.

/**
     * 带token和cookie的删除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{
            //创建内置httpClient对象
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;

            try {
                //创建Delete请求对象
                client = getCloseableHttpClient(httpUrl);
                HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(httpUrl);
                //添加Delete请求头
                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 {
    /**
     * 绕过验证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;
    }

    /**
     *  带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;
    }

    /**
     * 带token值和Cookie值得Get请求方法
     */
    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;
    }

    /**
     * 带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;
    }

    /**
     * 带Json格式参数传入post方法
     * 不带token和cookie
     */
    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;
    }



    /**
     * 带Json格式参数传入post方法
     * 带token和不带cookie
     */
    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;
    }

    /**
     * 带Json格式参数传入post方法
     * 带token和cookie
     */
    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;
    }

    /**
     * param格式参数传入post方法
     * 带token
     */
    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;
    }

    /**
     * param格式参数传入post方法
     * 带token和cookie
     */
    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;
    }

    /**
     * 带token和cookie的删除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{
            //创建内置httpClient对象
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;

            try {
                //创建Delete请求对象
                client = getCloseableHttpClient(httpUrl);
                HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(httpUrl);
                //添加Delete请求头
                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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闲小憨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值