如何使用Java处理HTTP请求和响应?

2023-08-22 17:00:58 浏览数 (1)

Java中有许多成熟的HTTP框架可以使用,例如Spring、Netty等。这些框架提供了各种HTTP处理器和工具类,使得HTTP请求和响应处理变得更加容易和高效。下面是一个简单的Java代码示例,演示如何使用Java处理HTTP请求和响应:

代码语言:javascript复制
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleHttpServer {
    private static final int PORT = 8080;

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(PORT);
        System.out.println("服务器已启动...");

        while (true) {
            Socket socket = serverSocket.accept(); // 等待客户端连接
            HttpRequest req = new HttpRequest(socket.getInputStream()); // 解析HTTP请求
            HttpResponse resp = new HttpResponse(socket.getOutputStream()); // 创建HTTP响应对象
            
            // 处理HTTP请求并发送响应结果
            String requestMethod = req.getMethod();
            if ("GET".equalsIgnoreCase(requestMethod)) {
                handleGetRequest(req, resp);
            } else if ("POST".equalsIgnoreCase(requestMethod)) {
                handlePostRequest(req, resp);
            }
            
            socket.close();
        }
    }

    // 处理GET请求
    private static void handleGetRequest(HttpRequest req, HttpResponse resp)
            throws IOException {
        String path = req.getPath();
        byte[] body = null;
        if ("/hello".equalsIgnoreCase(path)) {
            body = "Hello World!".getBytes();
        } else {
            resp.setStatus(404);
            body = "Resource Not Found".getBytes();
        }
        resp.setBody(body);
        resp.write();
    }

    // 处理POST请求
    private static void handlePostRequest(HttpRequest req, HttpResponse resp)
            throws IOException {
        // TODO: 实现对POST请求的处理
    }
}

class HttpRequest {
    private String method;
    private String path;

    public HttpRequest(InputStream input) throws IOException {
        byte[] buffer = new byte[1024];
        int len = input.read(buffer);
        if (len > 0) {
            String[] requestLine = new String(buffer, 0, len).split(" ");
            method = requestLine[0];
            path = requestLine[1];
        }
    }

    public String getMethod() {
        return method;
    }

    public String getPath() {
        return path;
    }
}

class HttpResponse {
    private OutputStream output;
    private int status = 200;
    private byte[] body;

    public HttpResponse(OutputStream output) {
        this.output = output;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public void setBody(byte[] body) {
        this.body = body;
    }

    public void write() throws IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("HTTP/1.1 ").append(status).append("rn")
          .append("Content-Type: text/plainrn")
          .append("Content-Length: ").append(body.length).append("rn")
          .append("rn");
        output.write(sb.toString().getBytes());
        output.write(body);
        output.flush();
    }
}

在这个例子中,我们创建了一个简单的HTTP服务器来监听指定端口的HTTP请求。当有客户端连接进来时,我们会解析HTTP请求并根据请求方法类型(GET或POST)来分发不同的处理方法,然后根据处理结果构建HTTP响应并将其返回给客户端。

HttpRequest和HttpResponse类分别代表了一个HTTP请求对象和HTTP响应对象。它们提供了一些方法来解析HTTP请求的参数和头部,并构建HTTP响应消息的状态和内容。在handleGetRequest和handlePostRequest方法中,我们可以编写自己的业务逻辑代码来实现对GET和POST请求的处理。需要注意的是,在处理HTTP请求和响应时,我们还需要确保线程安全,避免线程之间的资源竞争问题。

0 人点赞