okhttp的https访问示例

public static OkHttpClient.Builder buildOKHttpClient() {
    try {
        TrustManager[] trustAllCerts = buildTrustManagers();
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        builder.hostnameVerifier((hostname, session) -> true);
        return builder;
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
        return new OkHttpClient.Builder();
    }
}

 

public static String httpsPost(Request request) {
    String result = null;
    OkHttpClient client = buildOKHttpClient().build();
    try {
        Response response = client.newCall(request).execute();
        result = response.body().string();
    } catch (IOException e) {
        e.printStackTrace();
    }
    logger.info("result: {}", result);
    return result;
}
发布者:songJian   点击数:283   发布时间:2023-02-08 14:03:21   更新时间:2023-02-08 14:04:08
正在加载评论...
相关文章