如何使用SSL密钥库为apache HttpClient添加基本的抢先授权?

时间:2018-03-07 16:33:55

标签: java ssl basic-authentication apache-httpclient-4.x keystore

以下是我目前用于设置HttpClient的代码。但是对于一些webservice端点,我还需要使用用户名和密码添加Basic抢先授权。我尝试实现此处找到的代码或与此类似的代码:http://www.baeldung.com/httpclient-4-basic-authentication。但它没有成功,因为我找到的所有例子都没有包括SSL Keystore部分。有人可以帮我改进这段代码吗?提前谢谢!

public static HttpClient getHttpsClient(final String strWSEndPoint) throws Exception {

    HttpClient client = null;
    if (strWSEndPoint.contains("https://")) {

        final SSLContext sslcontext = getSSLContext();

        final SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1.2" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        client = HttpClients.custom().setSSLSocketFactory(factory).setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
        return client;
    } else {
        client = HttpClientBuilder.create().build();
        return client;
    }

}

private static SSLContext getSSLContext() throws Exception {
    final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());      
    final FileInputStream instreamkey = new FileInputStream(new File("whatever.jks"));      
    try {
        keyStore.load(instreamkey, "password".toCharArray());
    } finally {
        instreamkey.close();
    }
    final org.apache.http.conn.ssl.SSLContextBuilder objSSLContextBuilder = SSLContexts.custom().loadKeyMaterial(keyStore, "password".toCharArray());
    if (true) {
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        final FileInputStream instreamtrust = new FileInputStream(new File("whatever.jks"));            
        try {
            trustStore.load(instreamtrust, "whatever".toCharArray());
        } finally {
            instreamtrust.close();
        }
        objSSLContextBuilder.loadTrustMaterial(trustStore);
    }
    return objSSLContextBuilder.useTLS().build();
} 

如果有帮助,请附上SOAP UI中的图像。 here is the soap ui example

0 个答案:

没有答案