處理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();
你寫這是一個學習的過程?有許多現成的基於Java的Web服務器可用於處理HTTP請求。 – codebox
@codebox不,我對Java相當陌生。你能告訴我一些符合我需要的東西嗎? – meiryo