URLConnection URL

URLConnection URL

Summary: In this "URLConnection URL", you will know how to read a file with URLConnection class. Methods of classes URLConnection and URL are explained with example code, explanation and screenshots.

Are You Busy – A program on ServerSocket

The developer can easily know which port number on the server is busy so that he can connect to that port number which is not busy. We know earlier that the port numbers should be within 0 to 65,535 (both inclusive).

import java.net.ServerSocket;
import java.io.IOException;
public class AreYouBusy 
{
 public static void main(String args[]) 
 {
  for(int i = 0; i < 65536; i++) 
  {
    try 
    {
      ServerSocket sersock = new ServerSocket(i);
      sersock.close();        		
    }
    catch(IOException e) 
    {
      System.out.println( i + " Port is busy");
    }
  }
 }
}

URLConnection URL

Screenshot of AreYouBusy.java of URLConnection URL

ServerSocket sersock = new ServerSocket(i);

The job of java.net.ServerSocket is to bind the connection on the specified port number passed as parameter. This parameter is passed by the client system while requesting the connection to the server. Binding means the port number given to the client will not be given to another client until the first client disconnects himself. In client-server communication, it is the job of the server to bind the connection. The server uses ServerSocket class for it. To bind the connection, the server uses bind() method of ServerSocket. In this program, it is not used as we are not actually binding the connection; simply, the program is meant to know the port is busy or not. In the later programs, we use bind() method also.

sersock.close();

When the client disconnects, the server calls close() method. When the ServerSocket is closed, the port number on which the connection is bound earlier is released. Now, this port number can be given by the server to another client.

Practicing the Methods of URL

We know earlier, the system in the network requires an address. This unique address, in networking terms, is known as URI (Universal Resource Indicator). As the name indicates, it is an indicator or pointer to a system containing some resource of data. The resource (or system) can be in the same network or in a different network including WWW. The URI can be given in two ways – URL or URN. The URL stands for Uniform Resource Indicator comprising four digital number separated by three dots like 125.252.226.27. The URN stands for Uniform Resource Name which is just a name like rediff.com. You know earlier, if the name is given, it is exchanged with the numbered address and then connection is established. Names are given to remember the systems easily (it is difficult to remember 12 digit number).

Following list gives a few examples of URNs

http://www.rediff.com/
http://www.yahoo.co.in/
file:///D:/jyostna/oops/DynamicDemo.java
http://www.lorvent.com:7001/examplesWebApp/roses?password=srinivas

The complete URL can be divided into 5 parts. For example, http:// www.lorvent.com:7001/examplesWebApp/roses?password=srinivas can be divided as follows. If any part is omitted in the URL, the network assumes it due to standard conventions of networking.

  1. http - it is the protocol used in the communication
  2. www.lorvent.com - it is the name of the system to which the client is to be connected
  3. 7001 - it is the port number on which the service (or process) is available on the server required by the client
  4. examplesWebApp/roses - it is the fragment identifier and depends on the service configuration on the server
  5. password=srinivas - it is part of the request and represents the data passed to the server by the client. Basing on this data only server honors the client request
Parsing URLs

The above five pieces of the URL, like protocol and port number etc. can be retrieved by using the methods of class java.net.URL. Following program illustrates.

import java.net.*;
public class FivePieces
{
  public static void main(String args[])
  {
    try 
    {
      URL address = new URL("http://www.way2java.com:80/home.jsp#applets");                                
      System.out.println("Protocol Used: " + address.getProtocol());
      System.out.println("Host Name: " + address.getHost());
      System.out.println("Port Number: " + address.getPort());
      System.out.println("Resource Requested: " + address.getFile());
      System.out.println("Specific Topic: " + address.getRef());
    }
    catch(MalformedURLException e) 
    {
      System.out.println("The requested URL does not exist. " + e);
    }
  }
}

URLConnection URL

Screenshot of FivePieces.java of URLConnection URL

import java.net.*;

The above package is imported for two classes – URL and MalformedURLException.

The URL class comes with many methods of type getXXX() that return a lot of information of the URL address. The getRef() method returns the anchor part of the URL which is the actual part of the document home.jsp required by the client.

Reading straight with URL

We know an URL points to some resource of data on a system. Using openStream() method of URL class, we can read the data from the resource. In the following program, the file Morals.txt available in D:\jyothi is read and printed at DOS prompt.

import java.io.*;
import java.net.*;
public class ReadingWithURL
{
  public static void main(String args[])
  {
    try 
    {
      URL url = new URL("file:///D:/jyothi/Morals.txt");	
      InputStream is = url.openStream();
      int temp;
      while((temp = is.read() ) != -1)
      {
        System.out.print((char)temp);
      }
      is.close();
    }
    catch(MalformedURLException e) 
    {
      System.out.println("Resource does not exist. " +e);
    }  
    catch(IOException e) 
    {
      System.err.println("Unable read. " +e);
    } 
  }
}

URLConnection URL

Screenshot of ReadingWithURL.java of URLConnection URL

URL url = new URL("file:///D:/jyothi/Morals.txt");

Here, the URL points to the resource, Morals.txt available on the local system. The URL takes a string as parameter (the resource) and throws an exception java.net.MalformedURLException and is handled in the first catch block.

InputStream is = url.openStream();
is.read();

openStream() method of URL class returns an object of java.io.InputStream. This object is used to read the file Morals.txt. This method also throws MalformedURLException. The read() method of InputStream reads byte by byte from the resource file, Morals.txt. This method throws java.io.IOException.

System.out.print((char) temp);

The read() method returns an integer value and should be converted into a character. For more on reading of this type, refer I/O Streams topic.

Reading with URLConnection

URLConnection is an abstract class from java.net package. It operates on the link established by the client with the server. Programmer can use URLConnection to retrieve the data about the resource (say, documents) referred by the URL. An object of URLConnection can be used to read from or write data on the documents referred by URL. This class gives more flexibility of operation over the server resources to the programmer over URL.

The following program uses different methods of URL and also reads from a file referred by URL.

import java.io.*;
import java.net.*;     
import java.util.*;				
public class URLC    
{
  public static void main(String args[]) throws IOException
  {
    URL url = new URL("file:///D:/jyothi/Morals.txt");
    URLConnection con = url.openConnection(); 

    System.out.println("Source: " + con.getURL());  	        
    System.out.println("Today: "+ new Date(con.getDate())); 
    System.out.println("Type of the content in the file: " + con.getContentType());  
    System.out.println("Expiration date: " + con.getExpiration());  
    System.out.println("Creation/Modification date of source:  " + new Date(con.getLastModified()));
    System.out.println("Size of the content: " + con.getContentLength());  
			                                                    // reading from the file
    System.out.println("\n\tSee the contents of Morals.txt file:");

    InputStream istream = con.getInputStream();
    int k;              
    while((k = istream.read()) !=  -1)
    {
      System.out.print((char) k);
    }
    istream.close();
  }      
}

URLConnection URL

Screenshot of URLC.java

URL url = new URL("file:///D:/jyothi/Morals.txt");

Now the URL object url refers the resource in the form of file Morals.txt.

URLConnection con = url.openConnection( );

The openConnection() method of URL class returns an object of URLConnection, con. The con object points to the file, Morals.txt. With con object, we can read or write into the file Morals.txt and also know the particulars of the URL address.

The methods of URLConnection class, like getURL(), getDate(), getContentType(), getExpiration() and getLastModified() return the complete address as referred by the URL object, sending date of the resource referred by URL, the type of the content existing in the file (like html, plain text or image etc.), the expiration date of the resource (if the resource is a software) and the date of creation of the file Morals.txt or the latest modification date respectively.

InputStream istream = con.getInputStream();

The URLConnection class includes two methods getInputStream() and getOutputStream() that return an object of InputStream and OutputStream. These objects are useful to read from the resource or write to the resource.

Leave a Comment

Your email address will not be published.