用Java包com.sun.net.httpserver下面的类实现一个简单的http服务器demo

java的com.sun.net.httpserver包下的类提供了一个高层级的http服务器API,可以用来构建内嵌的http服务器。支持http和https。这些API提供了一个RFC 2616 (HTTP 1.1)和RFC 2818 (HTTP over TLS)的部分实现。
https://docs.oracle.com/en/java/javase/19/docs/api/jdk.httpserver/com/sun/net/httpserver/package-summary.html
在这里插入图片描述

下面来实现一个简单的demo。

代码示例:

package com.thb;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo {

    public static void main(String[] args) throws IOException {
        // 用端口号8082、backlog数量等于5创建一个HttpServer
        final HttpServer server = HttpServer.create(new InetSocketAddress(8082), 5);
        // 创建线程池
        final ExecutorService threads = Executors.newFixedThreadPool(3);
        // 设置线程池
        server.setExecutor(threads);
        // 启动HttpServer
        server.start();

        // 创建一个上下文
        HttpContext context = server.createContext("/hello");
        // 设置上下文的HttpHandler
        context.setHandler(
                new HttpHandler() {
                    // 实现接口的函数
                    public void handle(HttpExchange exchange) throws IOException {
                        // 开始发送响应给客户端
                        exchange.sendResponseHeaders(200, 0);
                        // 取得输出流,用来写入输出内容
                        OutputStream out = exchange.getResponseBody();
                        out.write("welcome! You are success.".getBytes());
                        out.flush();
                        out.close();
                        exchange.close();
                    }
                }
        );
    }

}

首先查看端口号8082,没有被占用:
在这里插入图片描述

运行上面的程序,再查看端口号8082,已经被占用了,说明http服务器已经启动了:
在这里插入图片描述

在浏览器中输入网址http://localhost:8082/hello,看到了期望的内容,说明http服务器能够正常访问了
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值