方法有很多,可以引入一些开源的jar组件,netty,jetty,tomcat,或者自己编写socket实现都能建立http服务。
这里分享一个不引入新的依赖快速创建http/https服务(有时候不支持引入一个新的依赖)
以下keystone证书文件生成可参考
https://blog.csdn.net/qq_18497293/article/details/121491160
测试用例代码如下:
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.security.KeyStore;
import java.util.concurrent.Executor;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
public class 原生Http服务器 {
public static void main(String[] args) {
try {
HttpServer httpServer = HttpServer.create(new InetSocketAddress(80), 0);
HttpHandler httpHandler = new HttpHandler() {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
System.out.println(httpExchange.getRequestURI().getQuery());
httpExchange.sendResponseHeaders(200, "hello".length());
httpExchange.getResponseBody().write("hello".getBytes());
}
};
httpServer.createContext("/", httpHandler);
httpServer.start();
HttpsServer hss = HttpsServer.create(new InetSocketAddress(18443), 0);
KeyStore ks = KeyStore.getInstance("JKS");
// 加载证书,这里使用jboss11的证书,,访问该服务 例如火狐浏览器修该 security.tls.version.min=1 解除不安全证书限制
InputStream resourceAsStream = 原生Http服务器.class.getResourceAsStream("application.keystore");
String password = "password";
ks.load(resourceAsStream, password.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, password.toCharArray());
SSLContext sslContext = SSLContext.getInstance("SSLv3");
sslContext.init(kmf.getKeyManagers(), null, null);
HttpsConfigurator conf = new HttpsConfigurator(sslContext);
hss.setHttpsConfigurator(conf);
hss.setExecutor(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
hss.createContext("/", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
System.out.println(exchange.getRequestURI().getQuery());
exchange.sendResponseHeaders(200, "hello https".length());
exchange.getResponseBody().write("hello https".getBytes());
}
});
hss.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
启动服务后,使用浏览器访问http://127.0.0.1
访问https://127.0.0.1:18443/