java用httpserver,写一个post的服务器
时间: 2024-03-23 19:39:36 浏览: 135
java写的http服务器
4星 · 用户满意度95%
好的,以下是一个使用Java HttpServer实现的简单POST服务器的代码示例。你可以根据自己的需求进行修改。
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class PostServer {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/post", new PostHandler());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on port 8080");
}
static class PostHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String requestMethod = exchange.getRequestMethod();
if ("POST".equals(requestMethod)) {
InputStream requestBody = exchange.getRequestBody();
byte[] requestBodyBytes = requestBody.readAllBytes();
String requestBodyString = new String(requestBodyBytes);
System.out.println("Received POST request with body: " + requestBodyString);
String response = "Server received your POST request with body: " + requestBodyString;
exchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
} else {
exchange.sendResponseHeaders(405, -1);
}
}
}
}
```
这个服务器会监听8080端口,接收POST请求,并将请求体内容打印到控制台,并返回一个简单的响应。你可以使用curl命令进行测试:
```bash
curl -X POST -d "Hello, World!" http://localhost:8080/post
```
这会向服务器发送一个POST请求,请求体为"Hello, World!",服务器会返回"Server received your POST request with body: Hello, World!"。
阅读全文