Java, Sockets and HTTP

Learnt a few things about the HTTP through Java. Here is a snippet code that will explain a lot.


public class SimpleSOCKET {

public static void main(String[] args) throws Exception {

String file = "/index.php";

Socket socket = new Socket("shoaib.no-ip.org", 80);
PrintWriter out = new PrintWriter(socket.getOutputStream(), false);
out.print("GET " + file + " HTTP/1.1\r\n");
out.print("Host: shoaib.no-ip.org\r\n");
out.print("Accept: text/plain, text/html, text/*\r\n");

out.print("\r\n");
out.flush();

String s;
BufferedReader buff = new BufferedReader(new InputStreamReader(socket.getInputStream()));

while ((s = buff.readLine())!=null) {
System.out.println(s + "\n");
}

socket.close();
out.close();
buff.close();

}
}

One thing to take care when working with HTTP/1.1 is that it requires you to send in a Host header.


out.print("Host: shoaib.no-ip.org\r\n");

Otherwise It will give you 403 Error (Forbidden). Whereas working with HTTP/1.0 this is completely optional.

One more thing I learned was that with HTTP/1.2 you can just use full path as your get request file. For example :-


String file = "http://shoaib.no-ip.org/index.php";
.
.
.
out.print("GET " + file + " HTTP/1.2\r\n");

Whereas HTTP/1.2 is even more complicated there are more criteria you need to satisfy, for example Connetion: closed, follow etc ...

So, this was basic HTTP client using Sockets and none of higher level HTTPConnection classes in java.