Send HTTP request manually via socket

Eng.Fouad picture Eng.Fouad · May 20, 2012 · Viewed 92.7k times · Source

When I send a normal HTTP request via a socket, the server does not respond with an OK response. I copied the HTTP header from Firefox. Here is the code:

Socket s = new Socket(InetAddress.getByName("stackoverflow.com"), 80);
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.print("GET / HTTP/1.1");
pw.print("Host: stackoverflow.com");
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String t;
while((t = br.readLine()) != null) System.out.println(t);
br.close();

However, here is the response I received:

HTTP/1.0 408 Request Time-out
Cache-Control: no-cache
Connection: close
Content-Type: text/html

<html><body><h1>408 Request Time-out</h1>
Your browser didn't send a complete request in time.
</body></html>

I know that I can do this by using URL.openStream(), but why doesn't the server identify the HTTP request when I send it manually?

Answer

Lycha picture Lycha · May 20, 2012

Two things:

  1. You should use println instead of print to print your entries to separate lines.
  2. HTTP request should end in a blank line (link). So add pw.println("");