java创建httpserver
时间: 2023-10-09 08:15:13 浏览: 94
要创建一个Java的HttpServer,你可以使用Java自带的HttpServer类。下面是一个创建HttpServer的示例代码:
```java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpServer;
public class ThreadHttpServer {
private static final int port = 8880;
private static final String Httpcontext = "/demo";
private static final int nThreads = 8;
public static void main(String\[\] args) {
HttpServer httpServer;
try {
httpServer = HttpServer.create(new InetSocketAddress(port), 0);
httpServer.createContext(Httpcontext, new HttpHandlerDemo());
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
httpServer.setExecutor(executor);
httpServer.start();
System.out.println("启动端口:" + port);
System.out.println("根节点:" + Httpcontext);
System.out.println("并发数:" + nThreads);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个示例代码创建了一个HttpServer实例,并指定了监听的端口号和根路径。同时,还设置了并发数来控制处理请求的线程池大小。你可以根据自己的需求修改这些参数。注意,这个示例代码使用了com.sun.net.httpserver.HttpServer类,所以你需要确保你的项目中引入了相关的依赖。
#### 引用[.reference_title]
- *1* *2* [java 自带HttpServer创建接口服务端](https://blog.csdn.net/xiaolenglala/article/details/102965011)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [Java实现http服务器](https://blog.csdn.net/fenglllle/article/details/118142770)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文