Java 調用Http和Https接口

Java調用Http接口和Https接口

大多數我們調用的接口都是Http的,很少有Https的接口,近期做了個項目就用到和Https接口的請求調用,和大家分享一下心得。Http接口和Https接口主要是區別還是Https存在一個證書驗證。針對Https和Http做出邏輯判斷,對Https接口的證書,咱們可以進行忽略。

話不多說,請看代碼

Service層,http和https的接口請求

httpURLConnection = (HttpURLConnection) addUrl.openConnection();
httpURLConnection.setConnectTimeout(TIMEOUT);
httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("accept", "*/*");
httpURLConnection.setRequestProperty("connection", "Keep-Alive");
httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
boolean addHttps = addUrl.toString().startsWith("https");
if (addHttps) {
    SSL addSSL = new SSL();
    addSSL.trustAllHosts((HttpsURLConnection) httpURLConnection);
    ((HttpsURLConnection) httpURLConnection).setHostnameVerifier(addSSL.DO_NOT_VERIFY);
    httpURLConnection.connect();
} else {
    httpURLConnection.connect();
}
if (httpURLConnection.getResponseCode() == 200) {
    inputStream = httpURLConnection.getInputStream();
    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line;
    stringBuffer = new StringBuffer();
    while ((line = bufferedReader.readLine()) != null) {
        stringBuffer.append(line);
    }
}

工具類 SSL

public class SSL {

    private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

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

    /**
     * 設置不驗證主機
     */
    public static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    /**
     * 信任所有
     *
     * @param connection
     * @return
     */
    public static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
        SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            SSLSocketFactory newFactory = sc.getSocketFactory();
            connection.setSSLSocketFactory(newFactory);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return oldFactory;
    }
}

這樣,針對不同類型的http和https接口都可以請求,如有不懂可以私信我哦!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章