beginner beginner - 27 days ago 16
Java Question

Java socket gets HTTP/1.1 400 Bad Request

Tried this code from this question. When just requesting

stackoverflow.com
, it gives the correct reply but when i try
http://stackoverflow.com/questions/10673684/send-http-request-manually-via-socket
, it returns
HTTP/1.1 400 Bad Request
. What causes this problem?

Here is the working code i got from the above link which gives that correct response from the server.

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


Tried to change it to the following...

Socket s = new Socket(InetAddress.getByName("stackoverflow.com"), 80);
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println("GET / HTTP/1.1");
pw.println("Host: http://stackoverflow.com/questions/10673684/send-http-request-manually-via-socket");
pw.println("");
pw.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String t;
while ((t = br.readLine()) != null) {
System.out.println(t);
}


Then the response is
HTTP/1.1 400 Bad Request
.

P.S. I am not planning to use any http libraries.

Answer

The problem lies within your request, which is not correct. If you replace your call to the PrintWriter with

pw.println ("GET /questions/10673684/send-http-request-manually-via-socket HTTP/1.1");
pw.println ("Host: stackoverflow.com");

it should work.

Comments