java原生http/https请求

package org.example;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;



public class App {

    public static void main(String[] args) throws IOException {
        postBody("https://www.baidu.com", "{\"test\":1}");
    }
    
    public static String postBody(String url, String requestJson) throws IOException {
        HttpURLConnection httpConn = null;
        BufferedReader bufferedReader = null;
        try {
            // connection
            URL realUrl = new URL(url);
            httpConn = (HttpURLConnection) realUrl.openConnection();

            // trust-https
            boolean useHttps = url.startsWith("https");
            if (useHttps) {
                HttpsURLConnection httpsConn = (HttpsURLConnection) httpConn;
                // 信任所有
                SSLSocketFactory trustAllHostsSSLSocketFactory = trustAllHostsSSLSocketFactory();
                // 根据本地证书信任
                SSLSocketFactory sslSocketFactory = certSSLSocketFactory();
                httpsConn.setSSLSocketFactory(trustAllHostsSSLSocketFactory);
                httpsConn.setHostnameVerifier((hostname, session) -> true);
            }

            // connection setting
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            httpConn.setUseCaches(false);
            httpConn.setReadTimeout(3 * 1000);
            httpConn.setConnectTimeout(3 * 1000);
            httpConn.setRequestProperty("connection", "Keep-Alive");
            httpConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            httpConn.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");

            // do connection
            httpConn.connect();

            // write requestBody
            if (requestJson != null && requestJson.length() > 0) {
                DataOutputStream dataOutputStream = new DataOutputStream(httpConn.getOutputStream());
                dataOutputStream.write(requestJson.getBytes(StandardCharsets.UTF_8));
                dataOutputStream.flush();
                dataOutputStream.close();
            }

            // valid StatusCode
            int statusCode = httpConn.getResponseCode();
            if (statusCode != 200) {
                System.out.println("not 200");
                throw new RuntimeException("statusCode: " + statusCode);
            }

            InputStream resultInputStream = httpConn.getInputStream();

//            // binary result and write temp file
//            String fileName = "test";
//            Path tempFile = Files.createTempFile(fileName, ".xlsx");
//            // remember to delete tempFile
//            // Files.delete(tempFile);
//            try ( OutputStream fileOutputStream = Files.newOutputStream(tempFile);){
//                byte[] buffer = new byte[1024];
//                int len;
//                while((len = resultInputStream.read(buffer))!=-1){
//                    fileOutputStream.write(buffer,0,len);
//                }
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }



            // json result
            bufferedReader = new BufferedReader(new InputStreamReader(resultInputStream, "UTF-8"));
            StringBuilder resultJson = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                resultJson.append(line);
            }
            return resultJson.toString();

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (httpConn != null) {
                httpConn.disconnect();
            }
        }
    }

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

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

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
        }};
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            // 信任所有证书
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            return sc.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static SSLSocketFactory certSSLSocketFactory() {
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            KeyStore keyStore = buildKeyStore();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);
            sc.init(null, tmf.getTrustManagers(), null);
            return sc.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static KeyStore buildKeyStore() throws Exception {
        // 获取自签名的证书
        List<X509Certificate> certs = loadHttpsCerts();
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        // 获得jdk证书库中的证书
        Arrays.stream(trustManagerFactory.getTrustManagers())
                .filter(manager -> manager instanceof X509TrustManager)
                .findFirst()
                .ifPresent(manager -> {
                    List<X509Certificate> jdkCerts = Arrays.asList(((X509TrustManager) manager).getAcceptedIssuers());
                    certs.addAll(jdkCerts);
                });
        certs.forEach(cert -> {
            try {
                keyStore.setCertificateEntry(cert.getSubjectDN().getName(), cert);
            } catch (KeyStoreException e) {
                throw new RuntimeException(e);
            }
        });
        return keyStore;
    }

    private static List<X509Certificate> loadHttpsCerts() throws IOException, CertificateException {
        List<X509Certificate> certs = new ArrayList<>(32);
        // 从路径读取证书文件,转化为inputStream
        InputStream certInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("证书名称");
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) factory.generateCertificate(certInputStream);
        certs.add(cert);
        return certs;
    }


}

你可能感兴趣的:(java,http,https)