zoukankan      html  css  js  c++  java
  • Java调用https接口,避免证书的方式

    一、使用httpClient调用

      1、使用maven添加依赖

    <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.3</version>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpmime</artifactId>
                <version>4.5.3</version>
            </dependency>
    View Code

      2、测试

    package com.moy.whymoy.test;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.conn.ssl.TrustStrategy;
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.ssl.SSLContexts;
    import org.apache.http.util.EntityUtils;
    
    import javax.net.ssl.*;
    import java.io.*;
    import java.net.URL;
    import java.security.KeyManagementException;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    
    /**
     * [Project]:whymoy  <br/>
     * [Email]:moy25@foxmail.com  <br/>
     * [Date]:2018/3/14  <br/>
     * [Description]:  <br/>
     *
     * @author YeXiangYang
     */
    public class Main {
    
        public static void main(String[] args) throws IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    
            String url = "https://kyfw.12306.cn/otn/";
            try (CloseableHttpClient httpClient = createHttpClient()) {
                HttpGet httpGet = new HttpGet(url);
                try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
                    HttpEntity entity = httpResponse.getEntity();
                    String result = EntityUtils.toString(entity);
                    EntityUtils.consume(entity);
                    
                    System.out.printf(result);
                }
            }
        }
    
    
        private static CloseableHttpClient createHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
            SSLContext sslcontext = SSLContexts.custom()
                    .loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
    
            SSLConnectionSocketFactory sslSf = new SSLConnectionSocketFactory(sslcontext, null, null,
                    new NoopHostnameVerifier());
    
            return HttpClients.custom().setSSLSocketFactory(sslSf).build();
        }
    }
    View Code

    二、使用原生HttpsURLConnection调用

    package com.moy.whymoy.test;
    
    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.InputStreamReader;
    import java.net.URL;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    
    /**
     * [Project]:whymoy  <br/>
     * [Email]:moy25@foxmail.com  <br/>
     * [Date]:2018/3/27  <br/>
     * [Description]:  <br/>
     *
     * @author YeXiangYang
     */
    public class Run {
    
        public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException {
    
            String url = "https://kyfw.12306.cn/otn/";
    
            SSLContext sc = createSslContext();
            HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier((s, sslSession) -> true);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.connect();
            StringBuilder result = new StringBuilder();
            try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
                String line;
                while (null != (line = br.readLine())) {
                    result.append(line).append("
    ");
                }
            }
            conn.disconnect();
    
            System.out.printf(result.toString());
        }
    
        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;
        }
    }
    View Code

    yexiangyang

    moyyexy@gmail.com


     

  • 相关阅读:
    java 菜单
    QT 让信号自由飞翔(骚操作)
    QT editLine 无法输入的问题
    易经初学体会
    Cgroup
    springboot pom 引用集合
    使用ab测试工具 进行并发测试
    intellij 设置-试验过的
    【iis错误码】IIS 服务 这些年遇到的错误码
    101个创业失败案例背后的20大原因
  • 原文地址:https://www.cnblogs.com/moy25/p/8658762.html
Copyright © 2011-2022 走看看