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;
public class ClientSocket {
    public static void main(String[] args) {
        try {
            // InetSocketAddress to specify a timeout for client
            // socket
            SocketAddress sockaddr = new InetSocketAddress(
                    "", 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(
            StringBuffer req = new StringBuffer();
            req.append("GET / HTTP/1.1\n");
            req.append("Accept-Language: en-US,en;q=0.5\n");
            String line;
            while ((line = in.readLine()) != null) {
        } catch (Exception e) {

* The HOST header must much the domain.


Possible Errors

  • If the timeout specified is not enugh you will get a 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 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


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