×

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 Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Java Math nextAfter() Method

The nextAfter() method of Math class returns the floating-point value adjacent to the first argument in direction of the second argument. Syntax: public static double nextAfter (double start, double direction)public static float...

2 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

How to initialize string array in Java

In this tutorial, we will learn how the string array is initialized in java. The initialization of string array in the java by using the NEW (it creates the object for...

3 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 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.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

Caesar Cipher Program in Java

It is among the most popular and straightforward encryption methods. With this method, each letter in the text is swapped out for a letter that is a certain number of...

3 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.