为了账号安全,请及时绑定邮箱和手机立即绑定

了解Apache HttpClient(Java)中的SSL

了解Apache HttpClient(Java)中的SSL

12345678_0001 2021-04-29 18:17:06
这里有一个自定义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(),似乎我们需要一些文件和一些密码?
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 194 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信