JAVA如何请求Https接口?

"HttpsClientUtils工具类"

Posted by 王晓东 on December 5, 2019

代码

package com.xxx.utils;

import com.alibaba.fastjson.JSONObject;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * @Author: 王晓东
 * @Date: 2019-10-28 13:36
 * @Email:lle@live.com
 */
public class HttpsClientUtils {
    public static String sendGet(String requestUrl, Map<String, String> requestHeader, String responseEncoding) throws KeyManagementException, NoSuchAlgorithmException, IOException {
        SSLContext sc = createSslContext();
        String result = "";
        BufferedReader reader = null;
        try {
            if (requestUrl == null || requestUrl.isEmpty()) {
                return result;
            }
            HttpsURLConnection connection = (HttpsURLConnection) new URL(requestUrl).openConnection();
            connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*");
            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Map.Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            connection.setSSLSocketFactory(sc.getSocketFactory());
            connection.setHostnameVerifier((s, sslSession) -> true);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.connect();
            if (responseEncoding == null || responseEncoding.isEmpty()) {
                responseEncoding = "UTF-8";
            }
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), responseEncoding));
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
            connection.disconnect();
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!");
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public static String sendUtf8Post(String requestUrl, JSONObject postBody){

        if(StringUtils.isEmpty(requestUrl)){
            return "";
        }
        BufferedReader reader = null;
        String result = "";
        try {
            SSLContext sc = createSslContext();
            HttpsURLConnection connection = (HttpsURLConnection) new URL(requestUrl).openConnection();
            connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.setSSLSocketFactory(sc.getSocketFactory());
            connection.setHostnameVerifier((s, sslSession) -> true);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(5000);
            connection.setDoOutput(true);
            connection.getOutputStream().write(postBody.toString().getBytes("utf-8"));

            InputStream inputStream = connection.getInputStream();
            byte[] bytes = new byte[0];
            bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            result = new String(bytes,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;

    }

    private static SSLContext createSslContext() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSL");

        sc.init(null, new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

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

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        }}, new java.security.SecureRandom());

        return sc;
    }
}