JAVA中有許多成熟的HTTP框架可以使用,例如Spring?.NETty等。這些框架提供了各種HTTP處理器和工具類,使得HTTP請求和響應處理變得更加容易和高效。下面是一個簡單的Java代碼示例,演示如何使用Java處理HTTP請求和響應:
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請求和響應時,我們還需要確保線程安全,避免線程之間的資源競爭問題。