0

我正在尝试通过 SSL 上的 get/post Web 服务调用来访问远程服务器。我以下列方式使用 apaches HttpClient:

HttpClient client = new HttpClient();
client.getHostConfiguration().setProxy("my_host", 443);
Credentials defaultcreds = new UsernamePasswordCredentials("dev", "password");
client.getState().setCredentials(new AuthScope("my_host", 443, AuthScope.ANY_REALM),  defaultcreds);

// Create a method instance.
GetMethod method = new GetMethod(url);

// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    new DefaultHttpMethodRetryHandler(3, false));

try {
    // Execute the method.
    int statusCode = client.executeMethod(method);

if (statusCode != HttpStatus.SC_OK) {
    System.err.println("Method failed: " + method.getStatusLine());
}

    // Read the response body.
    byte[] responseBody = method.getResponseBody();

// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));

} catch (HttpException e) {
    System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
    System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
    // Release the connection.
    method.releaseConnection();
}

它似乎在 POSTER 中工作,但我知道证书位于浏览器中,并且正在处理所有身份验证和证书处理。我需要编写代码来让这个响应在其他地方使用。有任何想法吗?当代码被推送到服务器时,这会成为一个问题吗?(是否需要不同的证书)。

编辑:这是添加的错误。

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
4

1 回答 1

0

解决此问题的正确方法是将主机 CA 添加到您的 JVM 信任库 ( <jre directory>/lib/security/cacerts)。您可以通过在浏览器中浏览到主机 URL、查看站点的证书(通常通过单击浏览器中 URL 旁边的锁定图标来完成)并将 CA 导出到文件来获取 CA 证书。keytool获得 .crt 文件后,您可以使用命令行工具将其导入 cacerts :

keytool -keystore cacerts -importcert -alias someName -file yourCertFilename

当提示输入密码时,默认为changeit

如果您不想将 CA 添加到默认信任库,则可以创建自己的信任库文件,用于在创建时SSLSocketFactory将其传递给HttpClient

keytool -keystore myTrustStore.jks -importcert -alias someName -file yourCertFilename

出现提示时输入您选择的密码。

KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream("myTrustStore.jks"), trustStorePassword);
SSLSocketFactory sf = new SSLSocketFactory(trustStore);
Scheme httpsScheme = new Scheme("https", 443, sf);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
HttpClient httpClient = new DefaultHttpClient(cm);

(上面的代码不在我的脑海中,还没有经过测试,但它应该给你的想法。)

或者,如果您希望 HTTPClient 完全绕过证书验证(我不推荐它),您可以创建一个TrustManager信任任何像这样的证书。

于 2013-08-28T19:52:45.633 回答