Java编写http服务器和http客户端,客户端能与服务端连接并展示响应成果服务器多线程处理客户端请求,可以实现GET、HEAD、POST请求,可以通过浏览器查看服务器信息的代码
时间: 2024-02-15 08:04:13 浏览: 70
以下是Java编写HTTP服务器和客户端的示例代码:
HTTP服务器:
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class HTTPServer implements Runnable {
private Socket clientSocket;
public HTTPServer(Socket clientSocket) {
this.clientSocket = clientSocket;
}
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("HTTP Server is running on port 8080.");
while (true) {
Socket clientSocket = serverSocket.accept();
Thread thread = new Thread(new HTTPServer(clientSocket));
thread.start();
}
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
OutputStream out = clientSocket.getOutputStream();
String requestLine = in.readLine();
System.out.println(requestLine);
String[] tokens = requestLine.split("\\s+");
String method = tokens[0];
String uri = tokens[1];
if (method.equals("GET")) {
doGet(uri, out);
} else if (method.equals("HEAD")) {
doHead(uri, out);
} else if (method.equals("POST")) {
doPost(uri, in, out);
} else {
doError(HttpStatus.BAD_REQUEST, out);
}
clientSocket.close();
} catch (IOException e) {
System.err.println(e);
}
}
private void doGet(String uri, OutputStream out) throws IOException {
File file = new File("." + uri);
if (file.exists() && file.isFile()) {
byte[] bytes = readFile(file);
out.write(getResponse(HttpStatus.OK, bytes.length, "text/html").getBytes());
out.write(bytes);
} else {
doError(HttpStatus.NOT_FOUND, out);
}
}
private void doHead(String uri, OutputStream out) throws IOException {
File file = new File("." + uri);
if (file.exists() && file.isFile()) {
byte[] bytes = readFile(file);
out.write(getResponse(HttpStatus.OK, bytes.length, "text/html").getBytes());
} else {
doError(HttpStatus.NOT_FOUND, out);
}
}
private void doPost(String uri, BufferedReader in, OutputStream out) throws IOException {
int contentLength = 0;
String line;
while ((line = in.readLine()) != null) {
if (line.equals("")) {
break;
}
if (line.startsWith("Content-Length: ")) {
contentLength = Integer.parseInt(line.substring("Content-Length: ".length()));
}
}
if (contentLength > 0) {
char[] buffer = new char[contentLength];
in.read(buffer, 0, contentLength);
String requestBody = new String(buffer);
System.out.println(requestBody);
}
out.write(getResponse(HttpStatus.OK, 0, "text/html").getBytes());
}
private void doError(HttpStatus status, OutputStream out) throws IOException {
out.write(getResponse(status, 0, "text/html").getBytes());
}
private String getResponse(HttpStatus status, int contentLength, String contentType) {
StringBuilder sb = new StringBuilder();
sb.append("HTTP/1.1 ").append(status.getCode()).append(" ").append(status.getMessage()).append("\r\n");
sb.append("Content-Length: ").append(contentLength).append("\r\n");
sb.append("Content-Type: ").append(contentType).append("\r\n");
sb.append("\r\n");
return sb.toString();
}
private static byte[] readFile(File file) throws IOException {
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
fileInputStream.read(bytes);
fileInputStream.close();
return bytes;
}
}
enum HttpStatus {
OK(200, "OK"),
BAD_REQUEST(400, "Bad Request"),
NOT_FOUND(404, "Not Found");
private final int code;
private final String message;
HttpStatus(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
```
HTTP客户端:
```java
import java.io.*;
import java.net.*;
public class HTTPClient {
public static void main(String[] args) throws Exception {
String method = "GET";
String uri = "/";
String requestBody = "";
if (args.length > 0) {
method = args[0];
}
if (args.length > 1) {
uri = args[1];
}
if (args.length > 2) {
requestBody = args[2];
}
Socket socket = new Socket("localhost", 8080);
OutputStream out = socket.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.write((method + " " + uri + " HTTP/1.1\r\n").getBytes());
out.write("Host: localhost\r\n".getBytes());
out.write("Connection: close\r\n".getBytes());
if (method.equals("POST")) {
out.write(("Content-Length: " + requestBody.length() + "\r\n").getBytes());
out.write("Content-Type: application/x-www-form-urlencoded\r\n".getBytes());
}
out.write("\r\n".getBytes());
if (method.equals("POST")) {
out.write(requestBody.getBytes());
}
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
socket.close();
}
}
```
以上代码实现了一个简单的HTTP服务器和客户端,服务器支持多线程处理客户端请求,可以处理GET、HEAD、POST请求,并且可以通过浏览器查看服务器信息。
阅读全文