所以在建立我的联系并接受一个连接之后:
ServerSocket serverSock = new ServerSocket(6789);
Socket sock = serverSock.accept();
当我在浏览器中输入localhost:6789/index.html
时,如何处理此传入的GET请求并返回index.html
? index.html
位于同一目录中。
首先,我想非常index.html
实际存在,如果不是,我会返回HTTP 404消息。然后我将关闭连接。
答案 0 :(得分:9)
处理GET和其他请求实际上非常简单,但您必须知道HTTP protocol的规范。
要做的第一件事是获取客户端的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();
答案 1 :(得分:2)