java-networking

URL Connections

The URLConnection class represents a connection to a URL and provides methods for interacting with the resource.

It is a four step process :

  1. Construct a URL object.
     URL url = new URL("http://www.example.com");
    
  2. Open a connection to the URL.
      URLConnection connection = url.openConnection();
    
  3. Get an input stream for reading from the URL.
     InputStream in = connection.getInputStream();
    
  4. Read from the input stream and close the connection.
     BufferedReader reader = new BufferedReader(new InputStreamReader(in));
     String line;
     while ((line = reader.readLine()) != null) {
         System.out.println(line);
     }
     reader.close();
    

Methods of URLConnection class

This class represents a connection to a URL and provides methods for interacting with the resource.

Reading the Header

i. Retrieving specific header fields

String contentType = connection.getContentType();
int contentLength = connection.getContentLength();
long date = connection.getDate();
long expiration = connection.getExpiration();
long lastModified = connection.getLastModified();

ii. Retrieving arbitrary header fields


// Print all the header fields

try{
    URL url = new URL("http://www.example.com");
    URLConnection connection = url.openConnection();
    for(int i=1;  ;i++){
        String headerFieldKey = connection.getHeaderFieldKey(i);

        if(headerFieldKey == null){
            break;
        }

            System.out.println(headerField + ": " + connection.getHeaderField(headerFieldKey));
 

    }
} catch(Exception e){
    e.printStackTrace();
}

Caches

The URLConnection class provides methods for controlling the cache behavior of the connection.

Pages accessed with GET over HTTP can and will be cached by default. The setUseCaches() method can be used to disable caching.

A page accessed with POST will not be cached by default.

try{
    URL url = new URL("http://www.example.com");
    URLConnection connection = url.openConnection();
    connection.setUseCaches(false);
    InputStream in = connection.getInputStream();
    // Read from the input stream
    in.close();
} catch(Exception e){
    e.printStackTrace();
}

HttpURLConnection

The HttpURLConnection class extends URLConnection and provides additional methods for working with HTTP connections.

The URLStreamHandler Class

This class is used to create a custom protocol handler for URLs.