java实战晋级技巧无证书访问https外部接口

Posted 小黄鸡1992

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java实战晋级技巧无证书访问https外部接口相关的知识,希望对你有一定的参考价值。

楼主公司需要调用gis服务器,但是服务器提供的https请求,同时公司也没有证书,这样会照成访问后不能直接调到接口,需要手动添加证书。所以用一下方式调用https接口可以避免上述情况。

java直接访问https请求,直接复制粘贴即可。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.*;

public class MyX509TrustManager implements X509TrustManager {

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

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

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


    public static void main(String[] args) throws Exception {
        SSLContext sslcontext = SSLContext.getInstance("SSL", "SunJSSE");
        sslcontext.init(null, new TrustManager[]{new MyX509TrustManager()}, new java.security.SecureRandom());
        URL serverUrl = new URL("地址");
        HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslsession) {
                //核心在这里,表示通过安全认证
                return true;
            }
        };
        //拼接请求
        HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
        HttpsURLConnection conn = (HttpsURLConnection) serverUrl.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/json");
        //必须设置false,否则会自动redirect到重定向后的地址
        conn.setInstanceFollowRedirects(false);
        conn.connect();
        String result = getReturn(conn);
        System.out.println(result);
    }

    //请求url获取返回的内容
    public static String getReturn(HttpsURLConnection connection) throws IOException {
        StringBuffer buffer = new StringBuffer();
        try (InputStream inputStream = connection.getInputStream();
             InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            String result = buffer.toString();
            return result;
        }
    }
}

以上是关于java实战晋级技巧无证书访问https外部接口的主要内容,如果未能解决你的问题,请参考以下文章

详细实战教程!部署Flask网站+域名访问+免费https证书

android中的https(无对等证书)问题

IP+HTTPS无证书导致Android手机中H5无法加载

实战http切换成https

Spring boot 配置https 实现java通过https接口访问

解析Java为什么不接受合法的HTTPS证书