Article updated on

Load URL with Java Sockets

This example shows how to connect to an URL using just java sockets. You may want this for a number of reasons.

  • Fast way to check if a given URL is working.
  • Check it an URL is taking too long to load.
  • Check if some response headers are being lost or not properly parsed.
package com.sockets.clientweb;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
public class ClientSocket {
    public static void main(String[] args) {
        try {
            // InetSocketAddress to specify a timeout for client
            // socket
            SocketAddress sockaddr = new InetSocketAddress(
                    "www.yahoo.com", 80);
            // creates the new Socket
            Socket s = new Socket();
            s.connect(sockaddr, 10000);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(s.getInputStream()));
            PrintWriter socketOut = new PrintWriter(
                    s.getOutputStream());
            StringBuffer req = new StringBuffer();
            req.append("GET / HTTP/1.1\n");
            req.append("Host: www.yahoo.com\n");
            req.append("Accept-Language: en-US,en;q=0.5\n");
            req.append("\n\n");
            socketOut.print(req);
            socketOut.flush();
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            socketOut.close();
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }    
}

* The HOST header must much the domain.

 

Possible Errors

  • If the timeout specified is not enugh you will get a java.net.SocketTimeoutException. 10 Seconds in this example
  • If you are using a firewall or the user you used to run the java sample doesn't have enough privileges you will get a java.net.BindException: Permission denied
  • If you don't send the right headers or if the server is prepared to reject this type of request you are prone to receive a HTTP/1.1 302 Found or 302 Moved

Notes

  • Mind using other libraries for much complex purposes such us org.apache.commons.httpclient.HttpClient or java.net.URL packages