2012-06-10 55 views
4

我有一個帶有'.pfx'擴展名和密碼的文件。JAVA - 使用SSL證書和HTTPS的簡單GET請求

我需要做的是發送一個簡單的GET請求到web服務並讀取響應正文。

我需要實現一個類似的方法:

String getHttpResponse(String url, String certificateFile, String passwordToCertificate){ 
    ... 
} 

我也試過證書「沒有密碼」轉換爲格式使用OpenSSL:已

Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM: 
openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes 

這樣的替代implementaion在我的方法可能是:

String getHttpResponse(String url, String certificateFile){ 
    ... 
} 

我會很感激你的幫助,我SPE但是我還沒有找到一個可以幫助我的例子,看起來我對於SSL和其他一些基本的假設沒有認識到問題。

+0

可以讓我知道環境(服務器),你的工作嗎? –

+0

該應用程序將在Apache Tomcat上運行。我發送請求的服務器是某種返回XML的SOAP web服務。 – dstronczak

回答

8

我終於找到了一個很好的解決方案(沒有創建自定義SSL上下文):

String getHttpResponseWithSSL(String url) throws Exception { 
    //default truststore parameters 
    System.setProperty("javax.net.ssl.trustStore", "/usr/lib/jvm/java-6-openjdk/jre/lib/securitycacerts"); 
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); 
    System.setProperty("javax.net.ssl.trustStoreType", "JKS"); 

    //my certificate and password 
    System.setProperty("javax.net.ssl.keyStore", "mycert.pfx"); 
    System.setProperty("javax.net.ssl.keyStorePassword", "mypass"); 
    System.setProperty("javax.net.ssl.keyStoreType", "PKCS12"); 


    HttpClient httpclient = new HttpClient(); 

    GetMethod method = new GetMethod(); 
    method.setPath(url); 

    int statusCode = httpclient.executeMethod(method); 
    System.out.println("Status: " + statusCode); 

    method.releaseConnection(); 

    return method.getResponseBodyAsString(); 
} 
+0

這樣,設置是全局性的,只能讀取一次。 – Bruno

+0

這對我來說很好。但是 - 如果我需要更改運行時的設置呢?你認爲再次設置System.setProperty會是非常錯誤的嗎? – dstronczak

+0

這並不是說它會是「錯誤的」,但更有可能它不起作用。 – Bruno

0

這個問題應該有你的答案:

HTTPClient-1.4.2: Explanation needed for Custom SSL Context Example

您需要使用的HttpClient創建請求,然後使用一個密鑰管理器。

+0

我試過這樣做,但我不確定應該使用什麼文件作爲「信任庫」... – dstronczak

+0

根據[this](http://docs.oracle.com/javase/6/docs/api /java/security/KeyStore.html#load%28java.io.InputStream,%20char[]%29),它可以爲空以創建一個空的密鑰庫。 – plasma147