通用技术 [https][charles][接口] https 接口自动化 demo 和 mac 端抓包方法

bauul · 2018年07月19日 · 最后由 bauul 回复于 2018年07月31日 · 1664 次阅读

缘由

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

charles 下载安装

环境

  • Mac OS X
  • java8
  • IDEA IDE

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 的使用

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 2 条回复 时间 点赞

哥,你可以来分享些物联网的东西拉~

恒温 回复

哈哈哈,很尴尬,虽然公司的名字里含物联网三个字,但目前所做的业务的物联网并没有直接的关系😅
现在在学业务的知识,太多了,我们是服装行业的 SaaS 解决方案

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册