[HttpClient]SSL雙向執行個體

來源:互聯網
上載者:User

標籤:

package com.jerry.httpclient;import java.io.File;import java.io.FileInputStream;import java.security.KeyStore;import javax.net.ssl.SSLContext;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;import org.apache.http.conn.ssl.SSLContexts;import org.apache.http.conn.ssl.TrustSelfSignedStrategy;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;/** *  * @author Jerry * @date 2015年2月12日 下午11:38:33 */public class SSLDemo {        public static final String KEY_STORE_TYPE_JKS = "jks";      public static final String KEY_STORE_TYPE_P12 = "PKCS12";           public static void main(String[] args) throws Exception{        KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE_P12);//伺服器發給瀏覽器的KeyStore        KeyStore trustStore = KeyStore.getInstance(KEY_STORE_TYPE_JKS);//瀏覽器發給伺服器的KeyStore        FileInputStream input = new FileInputStream(new File("d:\\tomcat.keystore"));        FileInputStream keyInput = new FileInputStream("d:\\mykey.p12");        trustStore.load(input, "123456".toCharArray());        keyStore.load(keyInput, "123456".toCharArray());        /*         * 使用2個keystore建立sslcontext         */        SSLContext sslContext = SSLContexts.custom().useTLS().                            loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())                            .loadKeyMaterial(keyStore, "123456".toCharArray())                            .build();        //通過sllcontext建立一個socket factory        SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext);        CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslFactory).build();        HttpGet get = new HttpGet("https://localhost:8443/services");        System.out.println("executing request: " + get.getRequestLine());        CloseableHttpResponse response = client.execute(get);        HttpEntity entity = response.getEntity();        if (entity != null) {            System.out.println("response content lenght: " + entity.getContentLength());        }        System.out.println(EntityUtils.toString(entity));        EntityUtils.consume(entity);    }}

 

[HttpClient]SSL雙向執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.