1

I asked a similar question in another thread but I think I'm just having trouble getting the syntax right at this point. I basically want to open a socket in Java, send a HTTP request message to get the header fields of a specific web page. My program looks like this so far:

            String server = "www.w3.org"; 
            int port = 80; 
            String uri = "/Protocols/rfc2616/rfc2616-sec5.html#sec5.1"

            Socket socket = new Socket(server, port); 

            PrintStream output = new PrintStream(socket.getOutputStream()); 
            BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            output.println("HEAD " + uri + " HTTP/1.1");

            //String response = ""; 
            String line = ""; 
            while((line = socketInput.readLine()) != null){
                System.out.println(line);  
            }

            socketInput.close();
            socket.close();

It doesn't really work. Or it doesn't work for all websites. If someone could just tell me the immediate problems with what I'm doing, that would be great. Thank you!

Cuthbert
  • 2,380
  • 4
  • 27
  • 55

2 Answers2

2

Change

output.println("HEAD " + uri + " HTTP/1.1");

to

output.println("HEAD " + uri + " HTTP/1.1");
output.println("Host: " + server);
output.println();

You have to send the Host header because usually there are more than one virtual host on one IP address. If you use HTTP/1.0 it works without the Host header.

palacsint
  • 26,486
  • 10
  • 75
  • 100
1

I would use some higher-level component, like HttpURLConnection (see here) or apache http components.

Community
  • 1
  • 1
Bozho
  • 554,002
  • 136
  • 1,025
  • 1,121