Java 上的服务器名称指示 (SNI)

2022-09-03 14:19:51

任何人都可以帮助我开始在Java中执行带有服务器名称指示的HTTP连接吗?

我正在尝试从我正在管理的网站请求内容。我一直在使用Apache的HttpClient库,但我对安全内容的请求失败了,因为该网站只使用SNI作为HTTPS,并且SNI没有在DefaultHttpClient中启用。我已经在Apache的HttpClient库中寻找了有关如何解决这个问题的说明,但是我看到最终得到了这个文档:http://hc.apache.org/httpclient-3.x/sslguide.html,它已经过时了(指的是当HttpClient和HttpCore是Apache的commons包的一部分时的代码)。

所以。。。任何帮助?


答案 1

您可能希望跟踪 https://issues.apache.org/jira/browse/HTTPCLIENT-1119

Java 7的底层客户端实现能够支持它,并通过SSSocketImpl#setHost(由sun.net.www.protocol.https.https调用)公开该功能。

在 Java 7 上使用

    new URL("https://cmbntr.sni.velox.ch/").openStream()

直到 HTTPCLIENT-1119 被修复


答案 2

这就是我在 org.apache.httpcomponents 的 httpclient v4.3+ 中所做的。

private HttpClientConnectionManager createConnectionManager(final SSLContext ctx) {
    LOG.info("Creating sslConnectionSocketFactory");
    final SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(ctx) {

        @Override
        protected void prepareSocket(SSLSocket socket) throws IOException {
            try {
                System.out.println("************ setting socket HOST property *************");
                PropertyUtils.setProperty(socket, HOST, Constants.SNI_HOST);
            } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException ex) {
                LOG.error(ex.getMessage());
            }
            super.prepareSocket(socket); 
        }

    };

    LOG.info("Creating connectionRegistry");
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslSF)
            .build();

    LOG.info("Creating poolingConnectionManager");
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setDefaultMaxPerRoute(MAX_CONNECTIONS_PER_ROUTE);
    connectionManager.setMaxTotal(MAX_CONNECTIONS);

    return connectionManager;
}

这就是我如何创建HttpClient

final KeyManager[] keyManagers = createKeyManagers();
final TrustManager[] trustManagers = createTrustManagers();
final SSLContext ctx = createSslContext(keyManagers, trustManagers);

final HttpClientConnectionManager connectionManager = createConnectionManager(ctx);

LOG.info("Creating httpClient");
HttpClient httpClient = HttpClients
        .custom()
        .setConnectionManager(connectionManager)
        .build();

推荐