Thursday, July 16, 2009

Java: Simple URLConnection program

Simple java program to Read from a URLConnection

/* SimpleURLConnection.java */

import java.net.*;
import java.io.*;

public class SimpleURLConnection
{
public static void main(String[] args) throws Exception
{
URL url= new URL("http://10.10.2.215/URLConnection/Test.jsp");//provide proper url

URLConnection connection = url.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line = "";

while((line=in.readLine()) != null)
{
System.out.println(line);
}

//closing resource
in.close();
connection=null;
}
}


Same above example in detail

/* SimpleURLConnection.java */


import java.net.URLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.net.MalformedURLException;
import java.io.IOException;

public class SimpleURLConnection
{
public static void main(String[] args)
{
//Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web.
URL url = null;
/*The abstract class URLConnection is the superclass of all classes that represent a communications
link between the application and a URL. Instances of this class can be used both to read from and to
write to the resource referenced by the URL*/
URLConnection connection = null;
BufferedReader in = null;

try
{
//Creates a URL object from the String representation.
url= new URL("http://10.10.2.215/URLConnection/Test.jsp");

}
catch (MalformedURLException ex)
{
//If the string specifies an unknown protocol.
System.out.println(ex);
}

try
{
//Returns a URLConnection object that represents a connection to the remote object referred to by the URL.
connection = url.openConnection();

in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line = "";

while((line=in.readLine()) != null)
{
System.out.println(line);
}
//closing BufferedReader
in.close();
}
catch (IOException ex)
{
//if an I/O exception occurs.
System.out.println(ex);
}

connection=null;
}
}