处理 GET 和其他请求其实很简单,但是你必须知道HTTP 协议的规范。
首先要做的是获取SocketInputStream
客户端的路径和要返回的文件的路径。HTTP 请求的第一行以这种形式出现: GET /index.html HTTP/1.1
. 这是一个执行此操作的代码示例:
SocketInputStream sis = sock.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(sis));
String request = br.readLine(); // Now you get GET index.html HTTP/1.1
String[] requestParam = request.split(" ");
String path = requestParam[1];
您创建一个新File
对象并检查该文件是否存在。如果文件不存在,则向客户端返回 404 响应。否则,您读取文件并将其内容发送回客户端:
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
File file = new File(path);
if( !file.exist()){
out.write("HTTP 404") // the file does not exists
}
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
String line;
while((line = bfr.readLine()) != null){
out.write(line);
}
bfr.close();
br.close();
out.close();
以下是完整的代码摘要:
ServerSocket serverSock = new ServerSocket(6789);
Socket sock = serverSock.accept();
InputStream sis = sock.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(sis));
String request = br.readLine(); // Now you get GET index.html HTTP/1.1`
String[] requestParam = request.split(" ");
String path = requestParam[1];
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
File file = new File(path);
if (!file.exists()) {
out.write("HTTP 404"); // the file does not exists
}
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
String line;
while ((line = bfr.readLine()) != null) {
out.write(line);
}
bfr.close();
br.close();
out.close();