×

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the URL refers to.

What is the URL?

  • The term "URL" stands for "Uniform Resource Locator." An URL is a type of string that helps find a site on the Internet (WWW).
  • A URL has two components:

     1.The protocol required to access the resource.

          2. Where the resource is located.

Features of the URLConnection class

  1. A class called URLConnection is abstract. The two subclasses, HttpURLConnection and JarURLConnection, are responsible for establishing connections between the client Java programme and URL resources found on the internet.
  2. The user can read from and write to any resource that a URL object references using the URLConnection class.
  3. Once a connection has been made and a URLConnection object has been created in the Java application, we may use it to read, write, or obtain further data, such as content length.

Constructors

1. secure URL connection (URL url):- It builds a connection to the requested URL.

URLConnection Class Methods

void addRequestProperty(String key, String value)A key-value pair is added to the generic request property.  
void connect()If a connection has not yet been made, it establishes one and creates a communications channel to the resource this URL belongs to.  
boolean getAllowUserInteraction()It returns the value of the object's allowUserInteraction property.
int getConnectionTimeout()The connect timeout setting is returned.
Object getContent()It obtains the information from the URL connection.
Object getContent(Class[] classes)It gets the data from the URL connection.
String getContentEncoding()The value of the header field for content-encoding is returned.  
int getContentLength()The content-length header field's value is what is returned.
long getContentLengthLong()The content-length header field's value, expressed as long, is returned.  
String getContentType()The date header field's value is what is returned.
long getDate()The date header field's value is what is returned.
static boolean getDefaultAllowUserInteraction()The allowUserInteraction field's default value is returned.  
boolean getDefaultUseCaches()It provides the useCaches flag of an URLConnection's default value.  
boolean getDoInput()The doInput flag of the URLConnection is returned along with its value.  
long getExpiration()The value of the expired header files is returned.  
static FileNameMap getFilenameMap()The filename map is loaded from a data file.  
String getHeaderField(int n)The nth header field's value is returned.  
String getHeaderField(String name)The name of the header field's value is returned.
long getHeaderFieldDate(String name, long Default)It displays the value, encoded as a number, of the provided field.  
int getHeaderFieldInt(String name, int Default)It provides a numerical representation of the specified field's value.  
String getHeaderFieldKey(int n)The key for the nth header field is returned.
long getHeaderFieldLong(String name, long Default)It gives the specified field's value, decoded as a number.  
Map<String, List<String>> getHeaderFields()The unmodifiable Map of the header field is returned.
long getIfModifiedSince()The ifModifiedSince field of the object's value is what is returned.
InputStream getInputStream()An input stream that reads from the open condition is returned.
long getLastModified()The last-modified header field's value is that which is returned.  
OutputStream getOutputStream()An output stream that writes to the connection is returned.  
Permission getPermission()It returns back a permission object that indicates the authorization required to establish the connection represented by the object  
int getReadTimeout()It provides the read timeout setting back.
Map<String, List<String>> getRequestProperties()It gives back the connection's value for the named general request property.
URL getURL()The URLConnection's URL field's value is what it returns.
boolean getUseCaches()The value of the useCaches field of the URLConnection is returned.
Static String guessContentTypeFromName(String fname)It attempts to determine the content type of an object based on the URL's specified to the file component.
static String guessContentTypeFromStream(InputStream is)It makes an effort to determine the kind of stream from the first characters of the input stream.
void setAllowUserInteraction(boolean allowuserinteraction)The allowUserInteraction field of this URLConnection is given a new value.  
static void setContentHandlerFactory(ContentHandlerFactory fac)An application's ContentHandlerFactory is configured by it.  
static void setDefaultAllowUserInteraction(boolean defaultallowuserinteraction)For all the next URLConnection objects, it changes the allowUserInteraction field's default value to the supplied value.
void steDafaultUseCaches(boolean defaultusecaches)It changes the useCaches field's default value to the specified value.  
void setDoInput(boolean doinput)For this URLConnection, it sets the supplied value for the doInput field's value.
void setDoOutput(boolean dooutput)The doOutput field for the URLConnection is set to the desired value.

How to obtain a URLConnection class object?

The object of the class URLConnection is returned by the openConnection() function of the URL class.

Syntax:

public URLConnection openConnection()throws IOException{}   

Displaying a webpage's source code using the URLProgram class

Numerous methods are available from the URLProgram class. Using the getInputStream() function, we can show every information on a website. It gives back all of the supplied URL's contents in a stream that may be read and shown.

URLProgram.java

import java.io.*;    
import java.net.*;    
public class URLProgram {    
public static void main(String[] args){    
try{    
URL url=new URL("http://www.microsoft.com");    
URLConnection urlcon=url.openConnection();    
InputStream stream=urlcon.getInputStream();    
int i;    
while((i=stream.read())!=-1){    
System.out.print((char)i);    
}    
}catch(Exception e){System.out.println(e);}    
}    
}    

Output:

URLConnection class in Java

Related Topics

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Stock Span Problem Using Stack in Java

The stock span problem is an issue in finance where we must determine a stock’s price span over all N days given a set of N daily price quotes. The...

6 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Java String contains() method

contains() method returns true only if it contains the given sequence of characters otherwise it returns false. syntax: public boolean contains(CharSequence sequence) parameters: sequence : It is the sequence to be searched. Returns: It returns true...

1 minute read.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 minutes read.

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

Ramanujan Number or Taxicab Number in Java

In this section, we will discuss what a Ramanujan number (also known as a Hardy-Ramanujan number) is and how to use a Java programme to determine if a given integer...

3 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

What’s new in Java 12

On March 19th, 2019, the Java 12th edition was released. After releasing this edition, they have decided to release every new edition every six months. This version is the advanced...

5 minutes read.

Types of Statements in Java

In natural languages, statements and sentences are roughly equivalent. In general, statements are similar to valid English sentences. We will talk about a statement in Java and the different kinds...

11 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.