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!

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

That was suggested to me, but I'd like to see if this will actually work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.