【发布时间】:2015-03-28 23:28:27
【问题描述】:
我正在使用 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 上的浏览器连接时,我得到“没有收到数据”,在 https://localhost:8080 上我得到“网页不可用” 没有抛出异常,而且它似乎运行没有问题,除了它什么都不做。
我使用 keytool 程序生成密钥库,但是我不熟悉这个过程,所以也许这是不正确的?但同样,它接受这一点,因为它正在设置密钥库和密钥管理器等。
我是否需要更改我的 HttpHandler 或上下文来处理 SSL 交换或其他什么?
【问题讨论】:
-
您没有收到 TLS 握手错误的事实表明证书等不是问题。相同的 URL 是否适用于 HTTP?
-
相同的 URL 用于 HttpServer,而不是 HttpsServer。使用浏览器时,https 或 http 请求都无法在当前状态下工作
标签: java ssl https server keystore