JAVA中有許多成熟的HTTP框架可以使用,例如Spring?.NETty等。這些框架提供了各種HTTP處理器和工具類,使得HTTP請(qǐng)求和響應(yīng)處理變得更加容易和高效。下面是一個(gè)簡(jiǎn)單的Java代碼示例,演示如何使用Java處理HTTP請(qǐng)求和響應(yīng):
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("服務(wù)器已啟動(dòng)...");
while (true) {
Socket socket = serverSocket.accept(); // 等待客戶端連接
HttpRequest req = new HttpRequest(socket.getInputStream()); // 解析HTTP請(qǐng)求
HttpResponse resp = new HttpResponse(socket.getOutputStream()); // 創(chuàng)建HTTP響應(yīng)對(duì)象
// 處理HTTP請(qǐng)求并發(fā)送響應(yīng)結(jié)果
String requestMethod = req.getMethod();
if ("GET".equalsIgnoreCase(requestMethod)) {
handleGetRequest(req, resp);
} else if ("POST".equalsIgnoreCase(requestMethod)) {
handlePostRequest(req, resp);
}
socket.close();
}
}
// 處理GET請(qǐng)求
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請(qǐng)求
private static void handlePostRequest(HttpRequest req, HttpResponse resp)
throws IOException {
// TODO: 實(shí)現(xiàn)對(duì)POST請(qǐng)求的處理
}
}
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();
}
}
在這個(gè)例子中,我們創(chuàng)建了一個(gè)簡(jiǎn)單的HTTP服務(wù)器來(lái)監(jiān)聽(tīng)指定端口的HTTP請(qǐng)求。當(dāng)有客戶端連接進(jìn)來(lái)時(shí),我們會(huì)解析HTTP請(qǐng)求并根據(jù)請(qǐng)求方法類型(GET或POST)來(lái)分發(fā)不同的處理方法,然后根據(jù)處理結(jié)果構(gòu)建HTTP響應(yīng)并將其返回給客戶端。
HttpRequest和HttpResponse類分別代表了一個(gè)HTTP請(qǐng)求對(duì)象和HTTP響應(yīng)對(duì)象。它們提供了一些方法來(lái)解析HTTP請(qǐng)求的參數(shù)和頭部,并構(gòu)建HTTP響應(yīng)消息的狀態(tài)和內(nèi)容。在handleGetRequest和handlePostRequest方法中,我們可以編寫(xiě)自己的業(yè)務(wù)邏輯代碼來(lái)實(shí)現(xiàn)對(duì)GET和POST請(qǐng)求的處理。需要注意的是,在處理HTTP請(qǐng)求和響應(yīng)時(shí),我們還需要確保線程安全,避免線程之間的資源競(jìng)爭(zhēng)問(wèn)題。