Abstract Class URLConnection in Java

digitization, transformation, binary

Abstract Class URLConnection in Java:

The abstract class URLConnection is the superclass of all the classes that represent a communication link between the application and a URL. Instances of this class can be used both to read from and to write to the resource reference by the URL.

A subclass of URLConnection supports a protocol-specific connection. A URLConnection can both read from and write to a URL.

Ads code goes here

URL.openConnection() returns a URLConnection instance. A URLConnection object is created when the openConnection() method is called for a URL object. At this point, the
actual connection has not yet been made, so setup parameters and general request properties can be modified for the specific connection. The various set methods control the setup parameters and request properties.

Then the actual connection is made by calling the connect() method. Finally, the remote object becomes available, and the header fields and the content are accessed using various get methods. we should use a URLConnection object when we want more control over the downloading of data than is available through the simpler URL methods.

The URLConnection class defines quite a few methods for setting parameters and retrieving information. Fortunately, for simple connections, all of the setup parameters and request properties can be left alone, as they all have reasonable default values. In most cases, you’ll only be interested in the getInputStream() and getContent() methods.

getInputStream() provides an InputStream that reads from the URL, while getContent() uses a ContentHandler to return an Object that represents the content of the resource. These methods are mirrored by the openStream() and getContent() convenience methods in the URL class.

connect() actually performs the network connection. Other methods that depend on being connected will call this method. getContent() returns the data referred to by the URL, parsed into an appropriate type of Object. If the URL protocol supports read and write operations, then getInputStream() and getOutputStream() respectively return input and output streams to the object referred to by the URL.

getContentLength(), getContentType(), getContentEncoding(), getExpiration(), getDate(), and getLastModified() return the appropriate information about the object referred to by the URL, if that information can be determined (e.g., from HTTP header fields). getHeaderField() returns an HTTP header field specified by name or by number. getHeaderFieldInt() and getHeaderFieldDate() return the value of a named header field parsed as an integer or a date.

There are a number of options that we need to specify to control how the URLConnection behaves. These options are set with the various set() methods and may be queried with corresponding get() methods. The options must be set before the connect() method is called. setDoInput() and setDoOutput() allow us to specify whether we use the URLConnection for input and/or output.The default is input-only. setAllowUserInteraction() specifies whether user interaction (such as typing a password) is allowed during the data transfer. The initial default is false.

setDefaultAllowUserInteraction() is a class method that allows us to change the default value for user interaction. setUseCaches() allows us to specify whether a cached version of the URL may be used. We can set this to false to force a URL to be reloaded. setDefaultUseCaches() sets the default value for setUseCaches().

setIfModifiedSince() allows you to specify that a URL should not be fetched (if it is possible to determine its modification date) unless it has been modified since a specified time.

In general, creating a connection to a URL is a multi-step process.

They are as follows:

  1. The connection object is created by invoking openConnection() on a URL.
  2. The setup parameters are manipulated and the actual connection to the remote objects is available for use.
  3. The remote object is available for use finally.

There are a set of properties that have a setter and a getter method. The first three in the before column also have corresponding default properties that specify the default values used in the subsequent requests where the properties are not specified. In common cases, all of these properties can be ignored as the pre-connection properties default to sensible values and the postcondition properties are often uninteresting. For more clients of this interface, there are only two interesting methods. They are:

  1. getInputStream()
  2. getObject()

They are mirrored in the URL class by the conventional method.

The openConnection() method returns a java.net.URLConnection,an abstract class whose subclasses represent the various types of URL connections.

Example:

  • If we try to connect an URL whose protocol is HTTP, the openConnection() method returns an HttpURLConnection object.
  • If we try to connect a URL whose representation is a jar, the openConnection() method returns a JarURLConnection object.

The structure of the class URLConnection is given as:

public abstract class java.net.URLConnection extends java.lang.Object{
// Protected Constructor
protected URLConnection(URL url);
// Class Variables
public static FileNameMap fileNameMap;
// Protected Instance Variables
protected boolean allowUserInteraction;
protected boolean connected;
protected boolean doInput;
protected boolean doOutput;
protected long ifModifiedSince;
protected URL url;
protected boolean useCaches;
// Class Methods
public static boolean getDefaultAllowUserInteraction();
public static String getDefaultRequestProperty(String key);
protected static String guessContentTypeFromName(String fname);
public static String guessContentTypeFromStream(InputStream is) throws IOException;
public static synchronized void setContentHandlerFactory(ContentHandlerFactory fac);
public static void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction);
public static void setDefaultRequestProperty(String key, String value);
// Public Instance Methods
public abstract void connect() throws IOException;
public boolean getAllowUserInteraction();
public Object getContent() throws IOException;
public String getContentEncoding();
public int getContentLength();
public String getContentType();
public long getDate();
public boolean getDefaultUseCaches();
public boolean getDoInput();
public boolean getDoOutput();
public long getExpiration();
public String getHeaderField(String name);
public String getHeaderField(int n);
public long getHeaderFieldDate(String name, long Default);
public int getHeaderFieldInt(String name, int Default);
public String getHeaderFieldKey(int n);
public long getIfModifiedSince();
public InputStream getInputStream() throws IOException;
public long getLastModified();
public OutputStream getOutputStream() throws IOException;
public String getRequestProperty(String key);
public URL getURL();
public boolean getUseCaches();
public void setAllowUserInteraction(boolean allowuserinteraction);
public void setDefaultUseCaches(boolean defaultusecaches);
public void setDoInput(boolean doinput);
public void setDoOutput(boolean dooutput);
public void setIfModifiedSince(long ifmodifiedsince);
public void setRequestProperty(String key, String value);
public void setUseCaches(boolean usecaches);
public String toString(); // Overrides Object
} 

The details of the class structure are given as follows:

protected boolean allowUserInteraction;

protected boolean allowUserInteraction represents a value of this field that can be set by the setAllowUserInteraction() method.Its value can be accessed by the getAllowUserInteraction() method.The default value is false unless the setDefaultAllowUserInteraction() method has been called, in which case that method call controls the default value. It’s default value is the value of the argument method to the last call to the setDefaultAllowUserInteraction() method.

if true this URL will be examined to allow user interactions such as popping up an authentication dialog. If false, then no user interaction is allowed.

protected boolean connected;

protected boolean connected represents a flag that indicates whether or not this object has established a connection to a remote host.

READ  Variables in Java

If false, this connection object has not created a communication link to the specified URL. If true, the communication link has been established.

protected boolean doInput;

protected boolean doInput represents a flag that indicates whether or not this connection is enabled for input. Setting this variable to true indicates that the connection is going to read data. The variable can be set by setDoInput() and retrieved by getDoInput(). The default value is true.

protected boolean doOutput;

protected boolean doOutput represents a flag that indicates whether or not this connection is enabled for output. Setting this variable to true indicates that the connection is going to write data. The variable can be set by setDoOutput() and retrieved by getDoOutput(). The default value is false.

public static FileNameMap fileNameMap;

public static FileNameMap fileNameMap represents a reference to the object that maps filename extensions to MIME type strings. This variable is used in guessContentTypeFromName().

protected long ifModifiedSince;

protected long ifModifiedSince represents a time value, specified as the number of seconds since January 1, 1970, that controls whether or not a resource is fetched based on its last modification time. Some protocols do not bother to retrieve a resource if there is a current
locally cached copy. However, if the resource has been modified more recently than ifModifiedSince, it is retrieved. If ifModifiedSince is 0, the resource is always retrieved. The variable can be set by setIfModifiedSince() and retrieved by getIfModifiedSince(). The default value is 0, which means that the resource must always be retrieved.

some protocols skip the fetching of the object unless the object has been modified more recently than a certain time. A non zero value is interpreted as the time corresponding to if modification since seconds since January 1, 1970, GMT. The object is fetched only if it has been modified more recently than that time. This variable is set by the set if modifiedSince() method. Its value can be accessed by the getIfModifiedSince() method. The fetching must always occur.

protected URL url;

protected URL url represents the resource to which this URLConnection connects. This variable is set to the value of the URL argument in the URLConnection constructor. It can be retrieved by getURL().

The url representing the remote object on the world wide web to which this connection is opened. The value of this field can be accessed by the getURL() method. The default value of this variable is the value of the URL argument in the URLConnection constructor.

protected boolean useCaches;

protected boolean useCaches represents a flag that indicates whether or not locally cached resources are used. Some protocols cache documents. If this variable is true, the protocol is allowed to use caching whenever possible. If it is false, the protocol must always try to retrieve the resource. The variable can be set by setUseCaches() and retrieved by getUseCaches().

The default value is true unless the setDefaultUseCaches() method has been called, in which case that method call controls the default value.

protected URLConnection(URL url);

protected URLConnection(URL url) constructor creates a URLConnection object to manage a connection to the destination specified by the given URL. The actual connection is not created.

Parameter
url – The URL to access.

public static boolean getDefaultAllowUserInteraction();

public static boolean getDefaultAllowUserInteraction() method returns the default value of the allowUserInteraction variable for all instances of URLConnection. The default value is false unless the setDefaultAllowUserInteraction() method has been called, in which case that method call controls the default value.

This method returns true if user interaction is allowed by default; false otherwise.

public static String getDefaultRequestProperty(String key);

public static String getDefaultRequestProperty(String key) method returns the default value for the request property named by the key parameter.

This method returns the default value of the named request property.

Parameter
key – The name of a request property.

protected static String guessContentTypeFromName(String fname);

protected static String guessContentTypeFromName(String fname) method uses the FileNameMap specified by the variable fileNameMap to return a MIME content type for the given filename.

This method returns a guess at the MIME type of the given file, or null if a guess cannot be made.

Parameter
fname – A String that contains the name of a file.

public static String guessContentTypeFromStream(InputStream is);

public static String guessContentTypeFromStream(InputStream is) method method looks at the first few bytes of an InputStream and returns a guess of the MIME content type. Note that the InputStream must support marks, which usually means that there is a BufferedInputStream at some level. Here are some strings that are recognized and the inferred content type:

StringMIME guess
#defimage/x-bitmap
<bodytext/html
GIF8image/gif
<!text/html
<head>text/html
<html>text/html
! XPM2image/x-pixmap

This method returns a guess at the MIME type of the given input stream, or null if a guess cannot be made.

Parameter
is – the input stream to inspect

public static synchronized void setContentHandlerFactory(ContentHandlerFactory fac);

public static synchronized void setContentHandlerFactory(ContentHandlerFactory fac) method method tells the URLConnection class to use the given ContentHandlerFactory object for all URLConnection objects. The purpose of this mechanism is to allow a program that hosts applets, such as a web browser, control over the creation of ContentHandler objects.

Parameter
fac – An object that implements ContentHandlerFactory.

public static void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction);

public static void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction) method sets the default value of the allowUserInteraction variable for all new instances of URLConnection.

Parameter
defaultallowuserinteraction – The new default value.

public static void setDefaultRequestProperty(String key,String value);

public static void setDefaultRequestProperty(String key,String value) method sets the default value of the request property named by the key parameter.

Parameter
key – The name of a request property.
value – The new default value.

public abstract void connect();

public abstract void connect() method actually establishes the connection When a URLConnection object is created, it is not immediately connected to the resource specified by its associated URL object.

If this method is called after the connection has been established, it does nothing.
Before the connection is established, various parameters can be set with the set methods. After the connection has been established, it is an error to try to set these parameters.

As they retrieve information about the resource specified by the URL object, many of the get methods require that the connection be established. If the connection has not been established when one of these methods is called, the connection is established implicitly.

public boolean getAllowUserInteraction();

public boolean getAllowUserInteraction() method returns the value of the allowUserInteraction variable for this URLConnection.

READ  Abstract Class Number in Java

This method returns true if user interaction is allowed for this connection; false otherwise.

public Object getContent()

public Object getContent() method retrieves the content of the resource specified by the URL object associated with this URLConnection.

If the connection for this object has not been established, the method implicitly establishes it.
The method returns an object that encapsulates the content of the connection. For example, for a connection that has content-type image/jpeg, the method might return an object that belongs to a subclass of Image, or for content type text/plain, it might return a String. The instanceof operator should determine the specific type of object that is returned.

The method first determines the content type of the connection by calling getContentType(). If this is the first time the content type has been seen, a content handler of type ContentHandler is created for the content type. Here are the steps that are taken to create a content handler:

  • If an application has set up a ContentHandlerFactory by calling etContentHandlerFactory(),
    the method calls the createContentHandler() method of that object to create the content handler. The content type is passed as a String argument to that method.
  • If no ContentHandlerFactory has been established, or the createContentHandler() method
    returns null, the method retrieves the value of the system property java.content.handler.pkgs. If this value is not null, it is interpreted as a list of packages separated by a vertical bar (|) characters. The method then tries to load the class named package.contentType, where package is the name of the first package in the list and contentType is formed by taking the content-type string and replacing every slash (/) character with a period (.) and every other nonalphanumeric character with an underscore ( _ ). If the class exists and is a subclass of ContentHandler, it is used as the ContentHandler for the content type. If the class does not exist, or if it exists but is not a subclass of ContentHandler, the method tries the next package in the list.
  • If the previous step fails to find an appropriate content handler, the method tries to load the class named sun.net.www.content.contentType, where contentType is formed by taking the content-type string and replacing every slash (/) character with a period (.) and every other nonalphanumeric character with an underscore ( _ ). If the class exists and is a subclass of ContentHandler, it is used as the ContentHandler for the content type. If the class does not exist, or if it exists but is not a subclass of ContentHandler, a UnknownServiceException is thrown.

This method returns an Object created from this URLConnection.

public String getContentEncoding();

public String getContentEncoding() method retrieves the content encoding of the resource specified by the URL object associated with this URLConnection. In other words, the method returns the value of the content-encoding header field. If the connection for this object has not been established, the method implicitly establishes it.

This method returns the content-encoding, or null if it is not known.

public int getContentLength();

public int getContentLength() method retrieves the content length of the resource specified by the URL object associated with this URLConnection. In other words, the method returns the value of the content-length header field. If the connection for this object has not been established, the method implicitly establishes it.

This method returns the content length or -1 if it is not known.

public String getContentType();

public String getContentType() method retrieves the content type of the resource specified by the URL object associated with this URLConnection. In other words, the method returns the value of the content-type header field. This string is generally a MIME type, such as image/jpeg or text/html. If the connection for this object has not been established, the method implicitly establishes it.

This method returns the content type, or null if it is not known.

public long getDate();

public long getDate() method retrieves the date of the resource specified by the URL object associated with this URLConnection. In other words, the method returns the value of the date header field. The date is returned as the number of seconds since January 1, 1970. If the connection for this object has not been established, the method implicitly establishes it.

This method returns the content date, or 0 if it is not known.

public boolean getDefaultUseCaches();

public boolean getDefaultUseCaches() method returns the default value of the useCaches variable for all instances of URLConnection. The default value is true, unless the setDefaultUseCaches() method has been called, in which case that method call controls the default value.

This method returns true if the use of caches is allowed by default; false otherwise.

public boolean getDoInput();

public boolean getDoInput() method returns the value of the doInput variable for this URLConnection.

This method returns true if this URLConnection is to be used for input; false otherwise.

public boolean getDoOutput();

public boolean getDoOutput() method returns the value of the doOutput variable for this URLConnection.

This method returns true if this URLConnection is to be used for output; false otherwise.

public long getExpiration();

public long getExpiration() method retrieves the expiration date of the resource specified by the URL object associated with this URLConnection. In other words, the method returns the value of the expires header field. The date is returned as the number of seconds since January 1, 1970. If the connection for this object has not been established, the method
implicitly establishes it.

This method returns The content expiration date, or if it is not known.

public String getHeaderField(int n);

public String getHeaderField(int n) method retrieves the value of the header field at index n of the resource specified by the URL object associated with this URLConnection. If the connection for this object has not been established, the method implicitly establishes it.

This method returns the value of the header field with the given index, or null if n is greater than the number of fields in the header.

Parameter
n – A header field index.

public String getHeaderField(String name);

public String getHeaderField(String name) method retrieves the value of the named header field of the resource specified by the URL object associated with this URLConnection. This method is a helper for methods like getContentEncoding() and getContentType(). If the connection for this object has not been established, the method implicitly establishes it.

READ  What Is Casting Upcasting and Downcasting in Java?

This method returns the value of the named header field, or null if the header field is not known or its value cannot be determined.

Parameter
name – A header field name.

public long getHeaderFieldDate(String name, long default);

public long getHeaderFieldDate(String name, long default) method retrieves the value of the named header field of the resource specified by the URL object associated with this URLConnection and parses it as a date value. The date is returned as the number of seconds since January 1, 1970. If the value of the header field cannot be determined or it is not a properly formed date, the given default value is returned. If the connection for this object has not been established, the method implicitly establishes it.

This method returns the value of the named header field parsed as a date value, or default if the field is missing or cannot be parsed.

Parameter
name – A header field name.
default – A default date value.

public int getHeaderFieldInt(String name, int default);

public int getHeaderFieldInt(String name, int default) method retrieves the value of the named header field of the resource specified by the URL object associated with this URLConnection and parses it as a number. If the value of the header field cannot be determined or it is not a properly formed integer, the given default value is returned. If the connection for this object has not been established, the method implicitly establishes it.

This method returns the value of the named header field parsed as a number, or default if the field is missing or cannot be parsed.

Parameter
name – A header field name.
default – A default value.

public String getHeaderFieldKey(int n);

public String getHeaderFieldKey(int n) method retrieves the name of the header field at index n of the resource specified by the URL object associated with this URLConnection. If the connection for this object has not been established, the method implicitly establishes it.

This method returns the name of the header field at the given index, or null if n is greater than the number of fields in the header.

Parameter
n – A header field index.

public long getIfModifiedSince();

public long getIfModifiedSince() method returns the value of the ifModifiedSince variable for this URLConnection.

This method returns the value of the ifModifiedSince variable.

public InputStream getInputStream();

public InputStream getInputStream() method returns an InputStream that reads the contents of the resource specified by the URL object associated with this URLConnection.

This method returns an InputStream that reads data from this connection.

public long getLastModified();

public long getLastModified() method retrieves the last-modified date of the resource specified by the URL object associated with this URLConnection. In other words, the method returns the value of the last-modified header field. The date is returned as the number of seconds since January 1, 1970. If the connection for this object has not been established, the method implicitly establishes it.

This method returns the content last-modified date, or if it is not known.

public OutputStream getOutputStream();

public OutputStream getOutputStream() method returns an OutputStream that writes to the resource specified by the URL object associated with this URLConnection.

This method returns an OutputStream that writes data to this connection.

public String getRequestProperty(String key);

public String getRequestProperty(String key) method returns the value of the requested property named by the key parameter.

This method returns the value of the named request property.

Parameter
key -The name of a request property.

public URL getURL();

public URL getURL() method returns a reference to the URL associated with this object. This is the value of the url variable for this URLConnection.

This method returns the URL that this connection accesses.

public boolean getUseCaches();

public boolean getUseCaches() method returns the value of the useCaches variable for this URLConnection.

This method returns true if this URLConnection uses caches; false otherwise.

public void setAllowUserInteraction(boolean allowuserinteraction);

public void setAllowUserInteraction(boolean allowuserinteraction) method sets the value of the allowUserInteraction variable for this URLConnection. This method must be called before this object establishes a connection.

Parameter
allowuserinteraction – A boolean value that indicates whether user interaction is allowed or not.

public void setDefaultUseCaches(boolean defaultusecaches);

public void setDefaultUseCaches(boolean defaultusecaches) method sets the default value of the useCaches variable for all new instances of URLConnection.

Parameter
defaultusecaches – The new default value.

public void setDoInput(boolean doinput);

public void setDoInput(boolean doinput) method sets the value of the doInput variable for this URLConnection. This method must be called before this object establishes a connection.

Parameter
doinput – A boolean value that indicates if this connection is to be used for input.

public void setDoOutput(boolean dooutput);

public void setDoOutput(boolean dooutput) method sets the value of the doOutput variable for this URLConnection. This method must be called before this object establishes a connection.

Parameter
dooutput – A boolean value that indicates if this connection is to be used for output.

public void setIfModifiedSince(long ifmodifiedsince);

public void setIfModifiedSince(long ifmodifiedsince) method sets the value of the ifModifiedSince variable for this URLConnection. This method must be called before this object establishes a connection.

Parameter
ifmodifiedsince – A time value, specified as the number of seconds since January 1, 1970.

public void setRequestProperty(String key, String value);

public void setRequestProperty(String key, String value) method sets the value of the request property named by the key parameter.

Parameter
key – The name of a request property.
value – The new value.

public void setUseCaches(boolean defaultusecaches);

public void setUseCaches(boolean defaultusecaches) method sets the value of the useCaches variable for this URLConnection. This method must be called before this object establishes a connection.

Parameter
defaultusecaches – A boolean value that indicates if this connection uses caches.

public String toString();

public String toString() method returns a string representation of this URLConnection.
This method returns a string representation of the URLConnection.

Apart from these methods, URLConnection class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • wait(long)

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *