Open In App

java.net.URLConnection Class in Java

Last Updated : 26 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL class. Secondly, with a URLConnection we can check the header sent by the server and respond accordingly, we can configure header fields used in client requests. We can also download binary files by using URLConnection.

Let us do discuss out major methods of this class

Method Description
addRequestProperty(String key, String value) This method is used for adding a general request property specified by key-value pair.
connect() This method is used for establishing connection to the resource specified by URL, if such connection has not already been established.
getAllowUserInteraction() This method returns the allowUserInteraction field for the object.
getConnectTimeout() This method returns setting for connection time-out.
getContent() This method is used for retrieving contents of URLConnection.
 getContent(Class[] classes) Retrieves the contents of this URL connection.
 getContentEncoding() Returns the value of the content-encoding header field
getContentLength() Returns the value of the content-length header field.
 getContentLengthLong()  Returns the value of the content-length header field as a long.
getContentType() Returns the value of the content-type header field
 getDate() Returns the value of the date header field.
getDefaultAllowUserInteraction() Returns the default value of the allowUserInteraction field.
 getDefaultRequestProperty(String key) The instance specific getRequestProperty method should be used after an appropriate instance of URLConnection is obtained.
getDefaultUseCaches() Returns the default value of a URLConnection’s useCaches flag.
 getDoInput() Returns the value of this URLConnection’s doInput flag.
getDoOutput() Returns the value of this URLConnection’s doOutput flag.
getExpiration() Returns the value of the expires header field.
getFileNameMap() Loads filename map (a mimetable) from a data file
 getHeaderField(int n)  gets value of nth header field.
 getHeaderField(String name) Returns the value of the named header field.
getHeaderFieldDate(String name, long Default) Returns the value of the named field parsed as date
 getHeaderFieldInt(String name, int Default) Returns the value of the named field parsed as a number.
getHeaderFieldKey(int n) Returns the key for the nth header field.
getHeaderFieldLong(String name, long Default) Returns the value of the named field parsed as a number.
getHeaderFields() Returns an unmodifiable Map of the header fields.
getIfModifiedSince() Returns the value of this object’s ifModifiedSince field.
getInputStream() Returns an input stream that reads from this open connection
getLastModified() Returns the value of the last-modified header field.
 getOutputStream() Returns an output stream that writes to this connection
getPermission() Returns a permission object representing the permission necessary to make the connection represented by this object.
getReadTimeout() Returns setting for read timeout.
getRequestProperties() Returns an unmodifiable Map of general request properties for this connection
getRequestProperty(String key) Returns the value of the named general request property for this connection
getURL() Returns the value of this URLConnection’s URL field.
getUseCaches() Returns the value of this URLConnection’s useCaches field.
guessContentTypeFromName(String fname) Tries to determine the content type of an object, based on the specified “file” component of a URL
guessContentTypeFromStream(InputStream is) Tries to determine the type of an input stream based on the characters at the beginning of the input stream.
setAllowUserInteraction(boolean allowuserinteraction Set the value of the allowUserInteraction field of this URLConnection
setConnectTimeout(int timeout) Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection
 setContentHandlerFactory(ContentHandlerFactory fac) Sets the ContentHandlerFactory of an application.
setDefaultAllowUserInteraction(boolean defaultallowuserinteraction) Sets the default value of the allowUserInteraction field for all future URLConnection objects to the specified value.
setDefaultRequestProperty(String key, String value) The instance specific setRequestProperty method should be used after an appropriate instance of URLConnection is obtained. Invoking this method will have no effect.
 setDefaultUseCaches(boolean defaultusecaches) Sets the default value of the useCaches field to the specified value.
setDoInput(boolean doinput) Sets the value of the doInput field for this URLConnection to the specified value.
setDoOutput(boolean dooutput) Sets the value of the doOutput field for this URLConnection to the specified value.
setFileNameMap(FileNameMap map) Sets the FileNameMap.
setIfModifiedSince(long ifmodifiedsince) Sets the value of the ifModifiedSince field of this URLConnection to the specified value
setReadTimeout(int timeout Sets the read timeout to a specified timeout, in milliseconds
setRequestProperty(String key, String value) Sets the general request property
setUseCaches(boolean usecaches Sets the value of the useCaches field of this URLConnection to the specified value.
 toString() Returns a String representation of this URL connection.

Implementation:

Example

Java




// Java Program to demonstrate URLConnection class
 
// Importing input output classes
import java.io.*;
// Importing java.net package
// consisting of all network classes
import java.net.*;
 
// Main class
// URLConnectionExample
public class GFG {
 
    // Main driver method
    public static void main(String[] args) throws Exception
    {
        // Try block to check for exceptions
        try {
 
            // Creating an object of URL class
 
            // Custom input URL is passed as an argument
            URL u = new URL("www.geeksforgeeks.com");
 
            // Creating an object of URLConnection class to
            // communicate between application and URL
            URLConnection urlconnect = u.openConnection();
 
            // Creating an object of InputStream class
            // for our application streams to be read
            InputStream stream
                = urlconnect.getInputStream();
 
            // Declaring an integer variable
            int i;
 
            // Till the time URL is being read
            while ((i = stream.read()) != -1) {
 
                // Continue printing the stream
                System.out.print((char)i);
            }
        }
 
        // Catch block to handle the exception
        catch (Exception e) {
 
            // Print the exception on the console
            System.out.println(e);
        }
    }
}


Output

java.net.MalformedURLException: no protocol: www.geeksforgeeks.com

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads