Java調用https介面,避免認證的方式

來源:互聯網
上載者:User

標籤:script   測試   技術   sts   entity   gets   方式   .net   display   

一、使用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]:[email protected]  <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]:[email protected]  <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("\n");            }        }        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

[email protected]

 

Java調用https介面,避免認證的方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.