Handling GET and other requests is actually very simple but you must know the specification of the HTTP protocol.
The first thing to do is to get the SocketInputStream
of the client and the path of the file to return. The first line of the HTTP request comes in this form: GET /index.html HTTP/1.1
. Here is a code example that does that:
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];
You create a new File
object and checks if that file exists. If the file does not exist, you return a 404 response to the client. Otherwise you read the file and send its content back to the client:
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();
Here is the complete code summary:
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();