我有一個Grizzly製作的REST服務器,它使用HTTPS並且可以和Firefox一起使用。下面的代碼:在Java中使用HTTPS和REST
//Build a new Servlet Adapter.
ServletAdapter adapter=new ServletAdapter();
adapter.addInitParameter("com.sun.jersey.config.property.packages", "My.services");
adapter.addInitParameter(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, SecurityFilter.class.getName());
adapter.setContextPath("/");
adapter.setServletInstance(new ServletContainer());
//Configure SSL (See instructions at the top of this file on how these files are generated.)
SSLConfig ssl=new SSLConfig();
String keystoreFile=Main.class.getResource("resources/keystore_server.jks").toURI().getPath();
System.out.printf("Using keystore at: %s.",keystoreFile);
ssl.setKeyStoreFile(keystoreFile);
ssl.setKeyStorePass("asdfgh");
//Build the web server.
GrizzlyWebServer webServer=new GrizzlyWebServer(getPort(9999),".",true);
//Add the servlet.
webServer.addGrizzlyAdapter(adapter, new String[]{"/"});
//Set SSL
webServer.setSSLConfig(ssl);
//Start it up.
System.out.println(String.format("Jersey app started with WADL available at "
+ "%sapplication.wadl\n",
"https://localhost:9999/"));
webServer.start();
現在,我試圖用Java實現它:
SSLContext ctx=null;
try {
ctx = SSLContext.getInstance("SSL");
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
ClientConfig config=new DefaultClientConfig();
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(null,ctx));
WebResource service=Client.create(new DefaultClientConfig()).resource("https://localhost:9999/");
//Attempt to view the user's page.
try{
service
.path("user/"+username)
.get(String.class);
}
並獲得:
com.sun.jersey.api.client.ClientHandlerException: 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
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:128)
at com.sun.jersey.api.client.Client.handle(Client.java:453)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:557)
at com.sun.jersey.api.client.WebResource.get(WebResource.java:179)
從例子,我已經在網絡上發現,它好像我需要設置一個Truststore然後設置某種TrustManager。這看起來像很多代碼和設置工作爲我的簡單的小項目。有沒有簡單的方法來說...我相信這個證書,並指向一個.cert文件?
非常好,但...我可以在代碼中設置trustStore和trustStorePassword而不是VM的參數嗎? – User1 2009-11-18 19:41:08
是 - 在調用SSL需要的方法之前,請使用System.setProperty(「javax.net.ssl.trustStore」,「<新建信任存儲庫的路徑>>」),並對javax.net.ssl執行相同的操作。 trustStorePassword。 – delfuego 2009-11-18 19:48:37
一個令人難過的部分是,不正確的文件名會給出一個非常模糊的異常:「java.security.InvalidAlgorithmParameterException:trustAnchors參數必須爲非空」 – User1 2009-11-18 20:27:16