0

I am trying to make an HTTPClient connection using sockets and can't figure it out. When I run the code, I get the following message;

HTTP/1.1 400 Bad Request
Date: Sun, 22 Apr 2012 13:17:12 GMT
Server: Apache/2.2.16 (Debian)
Vary: Accept-Encoding
Content-Length: 317
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.2.16 (Debian) Server at pvs.ifi.uni-heidelberg.de Port 80</address>
</body></html>

The code is here:

import java.net.*;
import java.io.*;

public class a1 {
  public static void main ( String[] args ) throws IOException {
    Socket s = null;

    try {
        String host = "host1";
        String file = "file1";
        int port = 80;

Here I am creating the socket:

         s = new Socket(host, port);

        OutputStream out = s.getOutputStream();
        PrintWriter outw = new PrintWriter(out, false);
        outw.print("GET " + file + " HTTP/1.1\r\n");
        outw.print("Accept: text/plain, text/html, text/*\r\n");
        outw.print("\r\n");
        outw.flush();           

        InputStream in = s.getInputStream();
        InputStreamReader inr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(inr);
        String line;

        while ((line = br.readLine()) != null) {
                System.out.println(line);
        }

    } 
    catch (UnknownHostException e) {} 
    catch (IOException e) {}

        if (s != null) {
                try {
                        s.close();
                }
                catch ( IOException ioEx ) {}
        }
  }
}   

Any help will be appreciated. Thank you.

theJollySin
  • 5,687
  • 6
  • 39
  • 55
user1349536
  • 35
  • 1
  • 4
  • Try this: http://stackoverflow.com/questions/1359689/how-to-send-http-request-in-java/1359700#1359700 – duffymo Apr 22 '12 at 13:26
  • 4
    Or you could just use Apache Commons http. – bmargulies Apr 22 '12 at 13:26
  • If you really want to write your own HTTP client (if this isn't just for fun, then don't and look the the comments above), you should try with HTTP 1.0 first and add a slash before the requested path: `"GET /" + file + " HTTP/1.0\r\n"`. – Philipp Reichart Apr 22 '12 at 13:32

1 Answers1

4

If you really, really want to write your own HTTP client (harder than it seems, but very educative), you are missing the required Host header in HTTP 1.1:

outw.print("Host: " + host + ":" + port + "\r\n");

See RFC 2616, section 14.23. Host:

A client MUST include a Host header field in all HTTP/1.1 request messages.

So your request is bad, it misses required Host header.

Tomasz Nurkiewicz
  • 311,858
  • 65
  • 665
  • 652