猿问

了解Apache HttpClient(Java)中的SSL

这里有一个自定义SSL的示例:https :

//hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java


/**

 * This example demonstrates how to create secure connections with a custom SSL

 * context.

 */

public class ClientCustomSSL {


public final static void main(String[] args) throws Exception {

    // Trust own CA and all self-signed certs

    SSLContext sslcontext = SSLContexts.custom()

            .loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),

                    new TrustSelfSignedStrategy())

            .build();

    // Allow TLSv1 protocol only

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(

            sslcontext,

            new String[] { "TLSv1" },

            null,

            SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    CloseableHttpClient httpclient = HttpClients.custom()

            .setSSLSocketFactory(sslsf)

            .build();

    try {


        HttpGet httpget = new HttpGet("https://httpbin.org/");


        System.out.println("Executing request " + httpget.getRequestLine());


        CloseableHttpResponse response = httpclient.execute(httpget);

        try {

            HttpEntity entity = response.getEntity();


            System.out.println("----------------------------------------");

            System.out.println(response.getStatusLine());

            EntityUtils.consume(entity);

        } finally {

            response.close();

        }

    } finally {

        httpclient.close();

    }

}

}

为什么我们需要那个?我已经测试了没有任何SSL内容的HttpClient请求,并且从HTTPS URL得到了正确的响应,没有错误。

如果我不添加任何SSLContext,会有什么问题?

如果重要的是使其更加安全,这条线是什么?:


.loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),

似乎我们需要一些文件和一些密码?


12345678_0001
浏览 195回答 1
1回答
随时随地看视频慕课网APP

相关分类

Java
我要回答