缘由

最近接手的项目是使用 https 协议的,对于 https 的抓包和接口自动化开始都是一脸茫然,从度娘那里查了一下,整理成了本文

charles 下载安装

环境

pom

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>${okhttp3.version}</version>
</dependency>

这里使用 3.10.0 的版本

demo

public class HttpsUtils {
    private static final MediaType JSON = MediaType.parse("application/json; " + "charset=utf-8");
    private static final OkHttpClient httpsClient;

    static {
        final int timeout = 120;

        httpsClient = new OkHttpClient().newBuilder()
                .connectTimeout(timeout, SECONDS)
                .readTimeout(timeout, SECONDS)
                .writeTimeout(timeout, SECONDS)
                .hostnameVerifier((s, sslSession) -> true)
                .sslSocketFactory(createSSLSocketFactory())
                .build();
    }

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory sSLSocketFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllManager()},
                    new SecureRandom());
            sSLSocketFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return sSLSocketFactory;
    }

    private static class TrustAllManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    public static Response getGetResponse(final String path) {
        log.debug("GET, path: " + path);
        Request request = new Request.Builder().url(path)
                .addHeader(JsonTestUtils.accessToken, JsonTestUtils.getApiTestProject().getGlobalHeaders().get(JsonTestUtils.getCurrentTestCase().getBaseUrl()))
                .build();
        return getExecuteResponse(request);
    }

    public static Response getPostResponse(final String path, String body) {
        Request request = new Request.Builder().url(path).post(RequestBody.create(JSON, body))
                .addHeader(JsonTestUtils.accessToken, JsonTestUtils.getApiTestProject().getGlobalHeaders().get(JsonTestUtils.getCurrentTestCase().getBaseUrl()))
                .build();
        log.debug("POST, path: " + path + ", body: " + body);
        return getExecuteResponse(request);
    }

    public static Response getPutResponse(final String path, String body) {
        Request request = new Request.Builder().url(path).put(RequestBody.create(JSON, body))
                .addHeader(JsonTestUtils.accessToken, JsonTestUtils.getApiTestProject().getGlobalHeaders().get(JsonTestUtils.getCurrentTestCase().getBaseUrl()))
                .build();
        log.debug("POST, path: " + path + ", body: " + body);
        return getExecuteResponse(request);
    }

    public static Response getDeleteResponse(final String path, String body) {
        Request request = new Request.Builder().url(path).delete(RequestBody.create(JSON, body))
                .addHeader(JsonTestUtils.accessToken, JsonTestUtils.getApiTestProject().getGlobalHeaders().get(JsonTestUtils.getCurrentTestCase().getBaseUrl()))
                .build();
        log.debug("POST, path: " + path + ", body: " + body);
        return getExecuteResponse(request);
    }

    public static Response postForm(String path, Map<String, Object> bodyMap) throws IOException {
        FormBody.Builder formBody = new FormBody.Builder();
        for (Map.Entry<String, Object> one : bodyMap.entrySet()) {
            formBody.add(one.getKey(), one.getValue().toString());
        }

        Request request = new Request.Builder()
                .url(path)
                .post(formBody.build())
                .build();

        Call call = httpsClient.newCall(request);

        return call.execute();
    }

    public static Response postFile(List<UploadFile> uploadFiles, final String path, Map<String, Object> bodyMap) throws IOException {
        MultipartBody.Builder multipartBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (Map.Entry<String, Object> one : bodyMap.entrySet()) {
            multipartBody.addFormDataPart(one.getKey(), one.getValue().toString());

        }
        if (uploadFiles != null) {
            for (UploadFile uploadFile : uploadFiles) {
                RequestBody fileBody = RequestBody.create(MultipartBody.FORM, new File(uploadFile.getFilePath()));
                multipartBody.addFormDataPart(uploadFile.getName(), uploadFile.getFileName(), fileBody);
            }
        }

        Request request = new Request.Builder()
                .url(path)
                .post(multipartBody.build())
                .build();

        Call call = httpsClient.newCall(request);

        return call.execute();
    }

    private static Response getExecuteResponse(Request request) {
        Response response = null;
        try {
            response = httpsClient.newCall(request).execute();
        } catch (ConnectException e) {
            log.debug(e.getMessage());
        } catch (IOException e) {
            log.debug("exception:" + e.getMessage());
            throw new RuntimeException(request.method() + " \"" + request.url() + "\" failed. ", e);
        }

        return response;
    }
}

一般来说是三种类型,提交 json,提交表单,提交文件
代码是从网上找来的,整理了一下,本人测试的时候直接在 main 方法里调了一下,没问题的
可以成功发送以上三种请求

reference

一个可用的 license
https 抓包的具体配置
OkHttp 中 https 的使用


↙↙↙阅读原文可查看相关链接,并与作者交流