我正在使用HttpServer类在Java中构建应用程序服务器。我通过HTTP使用纯文本通信完美地运行此服务器。但是,我希望使用HttpsServer类将其升级为使用SSL。 我使用这个问题作为工作的基础:Simple Java HTTPS server
我的服务器类如下:
public Server(Options options){
SSLContext sslContext = null;
try {
server = HttpsServer.create(new InetSocketAddress(8080), 0);
sslContext = SSLContext.getInstance("TLS");
char[] password = options.getSSLPassword().toCharArray();
KeyStore ks = KeyStore.getInstance ("JKS");
FileInputStream fis = new FileInputStream (options.getSSLKeystore());
ks.load ( fis, password );
KeyManagerFactory kmf = KeyManagerFactory.getInstance ( "SunX509" );
kmf.init ( ks, password );
TrustManagerFactory tmf = TrustManagerFactory.getInstance ( "SunX509" );
tmf.init ( ks );
sslContext.init ( kmf.getKeyManagers (), tmf.getTrustManagers (), null );
} catch (Exception e) {
e.printStackTrace();
}
HttpsConfigurator httpsConfigurator = new HttpsConfigurator(sslContext) {
@Override
public void configure(HttpsParameters httpsParameters) {
SSLContext sslContext = getSSLContext();
SSLParameters defaultSSLParameters = sslContext.getDefaultSSLParameters();
httpsParameters.setSSLParameters(defaultSSLParameters);
}
};
server.createContext("/", new HttpHandler() {
@Override
public void handle(HttpExchange t) throws IOException {
HttpsExchange s = (HttpsExchange)t;
s.getSSLSession();
String response = "<html><body>Hello world.</body></html>";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
});
server.setExecutor(Executors.newCachedThreadPool());
System.out.println("Starting server on port " + port + "...");
server.setHttpsConfigurator(httpsConfigurator);
server.start();
System.out.println("Server started successfully!");
}
这编译并运行正常,但是当我尝试通过localhost上的浏览器连接时:8080我得到&#34;没有收到数据&#34;并在https://localhost:8080我得到&#34;网页不可用&#34; 抛出没有例外,它似乎没有任何问题,除了它什么都不做之外。
我使用keytool程序生成密钥库,但是我不熟悉这个过程,所以这可能不正确?但同样,它接受了这一点,因为它正在设置密钥库和keyManagers等。
我是否需要更改HttpHandler或上下文才能处理SSL交换?
答案 0 :(得分:4)
我已经能够使用我在问题中提供的代码使用SSL。我相信我遇到的问题是因为我生成的密钥库。使用此命令生成它工作的密钥库:
keytool -genkey -alias alias -keyalg RSA -keystore keystore.jks -keysize 2048