Java内置HttpServer的使用

一、相关类

1.HttpServer

表示一个服务器实例,需要绑定一个IP地址和端口号

2.HttpContext

服务器监听器的上下文

3.HttpHandler

上下文对应的http请求处理器

4.HttpExchange

监听器回调时传入的参数,封装了http请求和响应的所有数据操作

二、使用

public class MyServer {

    public static void main(String[] args) throws IOException {
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(9090), 0);
        httpServer.createContext("/hello", new MyHandler());
        httpServer.start();
        System.out.println("server start...");
    }

    static class MyHandler implements HttpHandler {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String response = "Hello World";
            exchange.sendResponseHeaders(200, 0);
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes("UTF-8"));
            os.close();
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 17 中已经内支持 HTTP/2,可以使用 JDK 自带的 HttpServer 来创建一个 HTTP/2 的服务端。下面是一个简单的示例代码: ```java import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsServer; import com.sun.net.httpserver.HttpsParameters; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.security.KeyStore; public class Http2Server { public static void main(String[] args) throws Exception { int port = 8443; String keystorePath = "/path/to/keystore.jks"; String keystorePassword = "password"; SSLContext sslContext = SSLContext.getInstance("TLS"); // Load the keystore KeyStore keyStore = KeyStore.getInstance("JKS"); InputStream inputStream = new FileInputStream(keystorePath); keyStore.load(inputStream, keystorePassword.toCharArray()); // Initialize the key manager factory KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(keyStore, keystorePassword.toCharArray()); // Initialize the trust manager factory TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(keyStore); // Initialize the SSL context sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); // Create the HTTPS server HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress(port), 0); httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) { public void configure(HttpsParameters params) { try { // Initialize the SSL context SSLContext sslContext = SSLContext.getDefault(); SSLEngine engine = sslContext.createSSLEngine(); params.setNeedClientAuth(false); params.setCipherSuites(engine.getEnabledCipherSuites()); params.setProtocols(engine.getEnabledProtocols()); // Get the default parameters SSLParameters defaultSSLParameters = sslContext.getDefaultSSLParameters(); params.setSSLParameters(defaultSSLParameters); } catch (Exception ex) { ex.printStackTrace(); } } }); // Create the HTTP server HttpServer httpServer = HttpServer.create(new InetSocketAddress(port), 0); // Set the HTTP handler httpServer.createContext("/", new MyHttpHandler()); // Set the HTTPS handler httpsServer.createContext("/", new MyHttpsHandler()); // Start the servers httpServer.start(); httpsServer.start(); System.out.println("Server started on port " + port); } static class MyHttpHandler implements HttpHandler { public void handle(HttpExchange exchange) throws IOException { String response = "Hello, HTTP/2!"; exchange.sendResponseHeaders(200, response.getBytes().length); OutputStream os = exchange.getResponseBody(); os.write(response.getBytes()); os.close(); } } static class MyHttpsHandler implements HttpsHandler { public void handle(HttpExchange exchange) throws IOException { String response = "Hello, HTTPS/2!"; exchange.sendResponseHeaders(200, response.getBytes().length); OutputStream os = exchange.getResponseBody(); os.write(response.getBytes()); os.close(); } } } ``` 在该示例中,我们使用 HttpServer 和 HttpsServer 类来创建一个 HTTP/2 的服务端。我们通过加载一个 keystore 来设 HTTPS 服务的 SSL 上下文,并且将 HTTP 和 HTTPS 的请求分别交给 MyHttpHandler 和 MyHttpsHandler 来处理。当收到请求时,这两个处理器会分别返回 "Hello, HTTP/2!" 和 "Hello, HTTPS/2!" 的响应。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值