Java访问HTTPS类型的URL

在工作中,难免会遇到调用第三方接口的时候,而这些第三方接口可能为了安全,用的是https协议,那么此时必须要做一些手脚,才能对这些接口调用成功,这里自己做一下笔记。

有很多HTTP/HTTPS请求的插件,反正博主在Java中喜欢用okhttp3,关于okhttp3的API这里不再介绍,主要是下面的这个类和创建client的过程。

首先在pom.xml引入依赖:



    com.squareup.okhttp3
    okhttp
    3.10.0

然后写一个SSL配置类:

package com.shuixian.wechat.conf;

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/** HTTPS认证配置类
 * @author 秋枫艳梦
 * @date 2019-05-25
 * */
public class SSLConf {
    private static SSLSocketFactory sslSocketFactory;  //SSLSocketFactory对象

    /**
     *  返回SSLSocketFactory工厂
     * */
    public static SSLSocketFactory getSslSocketFactory() {
        return sslSocketFactory;
    }

    /**
     *  静态块,实例化SSLSocketFactory工厂对象
     * */
    static {
        SSLContext sslContext= null;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null,new TrustManager[]{new TrustAllManager()},new SecureRandom());
            sslSocketFactory=sslContext.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 静态内部类,实现X509TrustManager接口
     * */
    public static class TrustAllManager implements X509TrustManager {

        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

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

    /**
     *  静态内部类,实现HostnameVerifier接口
     * */
    public static class TrustAllHost implements HostnameVerifier {

        /** 此方法用于验证客户机,省略验证逻辑,保证返回true即可通过验证
         * @param s 认证字符串,类似于token
         * @param sslSession SSL会话
         * @return 是否通过验证
         * */
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    }
}

然后创建client的过程:

OkHttpClient client=new OkHttpClient.Builder().sslSocketFactory(SSLConf.getSslSocketFactory(),new SSLConf.TrustAllManager())
                    .hostnameVerifier(new SSLConf.TrustAllHost()).build();

这样创建出来的client,已经可以发送https类型的请求了,后续的创建request、获取response,还请各位移步okhttp3的API文档!

你可能感兴趣的:(技术杂谈,Java访问https)