在Java中使用本地HTTPS URL,需要遵循以下步骤:
keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048 -storetype jks
import com.sun.net.httpserver.HttpsServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.KeyStore;
public class HttpsServerExample {
public static void main(String[] args) throws Exception {
HttpsServer server = HttpsServer.create(new InetSocketAddress(8000), 0);
SSLContext sslContext = getSSLContext("keystore.jks", "password");
server.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
public void configure(HttpsParameters params) {
SSLParameters sslParams = getSSLContext().getDefaultSSLParameters();
params.setSSLParameters(sslParams);
}
});
server.createContext("/", new MyHandler());
server.start();
System.out.println("Server started at https://localhost:8000/");
}
private static SSLContext getSSLContext(String keyStoreFile, String password) throws Exception {
FileInputStream fis = new FileInputStream(keyStoreFile);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(fis, password.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, password.toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, null);
return sslContext;
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "Hello world!";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
https://localhost:8000/
,即可访问本地HTTPS服务器。需要注意的是,由于本地HTTPS服务器使用的是自签名证书,浏览器访问时会出现安全警告。可以通过将自签名证书导入到浏览器的信任证书列表中,来避免安全警告。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云