0% found this document useful (0 votes)
4 views9 pages

Java - URLConnection Class

The Java URLConnection class is an abstract class that represents various types of URL connections, allowing for both reading from and writing to resources referenced by URLs. It includes methods for setting connection parameters, retrieving content, and managing request properties. An example program demonstrates how to connect to an HTTP URL and read its content line by line.

Uploaded by

codespeedcode
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

Java - URLConnection Class

The Java URLConnection class is an abstract class that represents various types of URL connections, allowing for both reading from and writing to resources referenced by URLs. It includes methods for setting connection parameters, retrieving content, and managing request properties. An example program demonstrates how to connect to an HTTP URL and read its content line by line.

Uploaded by

codespeedcode
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Home Java Java - URLConnection Class

Java - URLConnection Class

Java URLConnection Class


[Link], is an abstract class whose subclasses represent the various
types of URL connections. Instances of this class can be used both to read from and to
write to the resource referenced by the URL.

For example −

If you connect to a URL whose protocol is HTTP, the [Link]() method


returns an HttpURLConnection object.

If you connect to a URL that represents a JAR file, the [Link]()


method returns a JarURLConnection object, etc.

Steps to make a connection to a URL

Following are the steps to make a connectiion to the URL and start processing.

Invoke [Link]() method to get connection object.

Update setup parameters and general request properties as required using


connection object various setter methods.

Create a connection to remote object using connect() method of connection object.

Once remote object is available, access the content/headers of the remote object.

URLConnection Class Declaration

public abstract class URLConnection


extends Object

URLConnection Class Fields

[Link]. Field & Description

protected boolean allowUserInteraction

1 If true, this URL is being examined in a context in which it makes sense to allow user
interactions such as popping up an authentication dialog.

protected boolean connected


2
If false, this connection object has not created a communications link to the specified URL.

protected boolean doInput


3
This variable is set by the setDoInput method.

protected boolean doOutput


3
This variable is set by the setDoOutput method.

protected long ifModifiedSince

4 Some protocols support skipping the fetching of the object unless the object has been
modified more recently than a certain time.

protected URL url

5 The URL represents the remote object on the World Wide Web to which this connection is
opened.

protected boolean useCaches

6
If true, the protocol is allowed to use caching whenever it can.

URLConnection Class Methods


The URLConnection class has many methods for setting or determining information about
the connection, including the following −

[Link]. Method & Description

void addRequestProperty(String key, String value)


1
Adds a general request property specified by a key-value pair.

boolean getAllowUserInteraction()
2
Returns the value of the allowUserInteraction field for this object.

int getConnectTimeout()
3
Returns setting for connect timeout.

Object getContent()
4
Retrieves the contents of this URL connection.

Object getContent(Class[] classes)


5
Retrieves the contents of this URL connection.

String getContentEncoding()
6
Returns the value of the content-encoding header field.

int getContentLength()
7
Returns the value of the content-length header field.

long getContentLengthLong()
8
Returns the value of the content-length header field as long.

String getContentType()
9
Returns the value of the content-type header field.

long getDate()

10
Returns the value of the date header field.
static boolean getDefaultAllowUserInteraction()
11
Returns the default value of the allowUserInteraction field.

boolean getDefaultUseCaches()

12
Returns the default value of a URLConnection's useCaches flag.

static boolean getDefaultUseCaches(String protocol)

13
Returns the default value of the useCaches flag for the given protocol.

boolean getDoInput()

14
Returns the value of this URLConnection's doInput flag.

boolean getDoOutput()
15
Returns the value of this URLConnection's doOutput flag.

long getExpiration()
16
Returns the value of the expires header field.

static FileNameMap getFileNameMap()

17
Loads filename map (a mimetable) from a data file.

String getHeaderField(int n)

18
Returns the value for the nth header field.

String getHeaderField(String name)


19
Returns the value of the named header field.

long getHeaderFieldDate(String name, long Default)


20
Returns the value of the named field parsed as date.

int getHeaderFieldInt(String name, int Default)


21
Returns the value of the named field parsed as a number.

22 String getHeaderFieldKey(int n)
Returns the key for the nth header field.

long getHeaderFieldLong(String name, long Default)


23
Returns the value of the named field parsed as a number.

Map<String,List<String>> getHeaderFields()
24
Returns an unmodifiable Map of the header fields.

long getIfModifiedSince()

25
Returns the value of this object's ifModifiedSince field.

InputStream getInputStream()

26
Returns an input stream that reads from this open connection.

int getLastModified()

27
Returns the value of the last-modified header field.

OutputStream getOutputStream()
28
Returns an output stream that writes to this connection.

Permission getPermission()

29 Returns a permission object representing the permission necessary to make the connection
represented by this object.

int getReadTimeout()

30 Returns setting for read timeout. 0 return implies that the option is disabled (i.e., timeout
of infinity).

Map<String,List<String>> getRequestProperties()

31
Returns an unmodifiable Map of general request properties for this connection.

String getRequestProperty(String key)


32
Returns the value of the named general request property for this connection.
URL getURL()
33
Returns the value of this URLConnection's URL field.

boolean getUseCaches()
34
Returns the value of this URLConnection's useCaches field.

static String guessContentTypeFromName(String fname)

35 Tries to determine the content type of an object, based on the specified "file" component of
a URL.

static String guessContentTypeFromStream(InputStream is)

36 Tries to determine the type of an input stream based on the characters at the beginning of
the input stream.

void setAllowUserInteraction(boolean allowuserinteraction)

37
Set the value of the allowUserInteraction field of this URLConnection.

void setConnectTimeout(int timeout)

38 Sets a specified timeout value, in milliseconds, to be used when opening a communications


link to the resource referenced by this URLConnection.

static void setContentHandlerFactory(ContentHandlerFactory fac)

39
Sets the ContentHandlerFactory of an application.

static void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction)

40 Sets the default value of the allowUserInteraction field for all future URLConnection objects
to the specified value.

void setDefaultUseCaches(boolean defaultusecaches)

41
Sets the default value of the useCaches field to the specified value.

static void setDefaultUseCaches(String protocol, boolean defaultVal)


42
Sets the default value of the useCaches field for the named protocol to the given value.
void setDoInput(boolean doinput)
43
Sets the value of the doInput field for this URLConnection to the specified value.

void setDoOutput(boolean dooutput)

44
Sets the value of the doOutput field for this URLConnection to the specified value.

static void setFileNameMap(FileNameMap map)

45
Sets the FileNameMap.

void setIfModifiedSince(long ifmodifiedsince)

46
Sets the value of the ifModifiedSince field of this URLConnection to the specified value.

void setReadTimeout(int timeout)


47
Sets the read timeout to a specified timeout, in milliseconds.

void setRequestProperty(String key, String value)

48
Sets the general request property.

void setUseCaches(boolean usecaches)


49
Sets the value of the useCaches field of this URLConnection to the specified value.

String toString()

50
Returns a String representation of this URL connection.

Extends

This class extends following classes

[Link]

Example of URLConnection Class Methods


The following URLConnectionDemo program connects to a URL entered from the command
line.

If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and
the data in the resource is read one line at a time.

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class URLConnectionDemo {


public static void main(String [] args) {
try {
URL url = new URL("[Link]
URLConnection urlConnection = [Link]();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
}else {
[Link]("Please enter an HTTP URL.");
return;
}

BufferedReader in = new BufferedReader(


new InputStreamReader([Link]()));
String urlString = "";
String current;

while((current = [Link]()) != null) {


urlString += current;
}
[Link](urlString);
} catch (IOException e) {
[Link]();
}
}
}

A sample run of this program will produce the following result −

Output

$ java URLConnectionDemo

.....a complete HTML content of home page of [Link].....

You might also like