×

HttpURLConnection

HttpURLConnection

Protocol

It is a standard set of rules that allow electronic devices to communicate with each other.

The http protocol

The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide Web. The http is a TCP/IP based communication protocol that is used to deliver data on the World Wide Web.

The http protocol is the client server-based architecture where web browsers, robots and search engines, etc., acts like http clients, and the server acts as a server.

The http client requests a URL, which is having a protocol version, a domain name followed by the file or directories name. The http server responds, including the message’s protocol version and a success or error code, followed by a MIME-like message containing server information, entity meta-information, and possible entity-body content.

HttpURLConnection

It is a http specific URLConnection. It works for http protocol only. You can get information about any http URL such as header information, status code, response code by using the HttpURLConnection class.

Features:

  • It is an abstract class directly extending from the URLConnection class.
  • It is a http specific URLConnection, works for http protocol only. It extends all the functionality of its parent class with additional http related features.

Getting object of HttpURLConnection class:

 1. public URLConnection openConnection()throws IOException()
{
//returns the object of URLConnection class.
}
2.  By typecasting it to HttpURLConnection type as given we get object of the HttpURLConnection.
URL url=new URL("http://www.javatpoint/java-tutorial");
HttpURLConnection hcon=(HttpURLConnection)url.openConnection(); 

Explanation:

  1. Creating the URL object by using the

URL url=new URL(“http://www.javatpoint/java-tutorial”);

  • Obtain a URLConnection object by calling openConnection() of the URL class and casting the result to HttpURLConnection.

HttpURLConnection hcon=(HttpURLConnection)url.openConnection();

Methods in HttpURLConnection class:

Method Description
public boolean getInstanceFollowRedirects() It returns true or false depending on the automatic instance redirection set or not.
public InputStream getErrorStream() It gets the error stream if the server cannot be connected or some error occurred. It can contain information about how to fix the error.
public Permission getPermission()  It returns permission required to connect to the server.
public void setChunkedStreamingMode(int n)throws IllegalStateException This mode is used when the content length is not known. Instead of creating a buffer of fixed length and writing it to the server, content is broken into chunks and then written. Not all servers support this mode.
public boolean usingProxy() It returns true if the connection is established using a proxy, else false.  
public void disconnect ()  It indicates that other requests to the server are disconnected.
public static boolean getFollowRedirects() It returns true or false depending upon if there is an automatic redirection or not.
public void setFollowRedirects(boolean b) It sets whether a 3xx response code requests redirect automatically or not.
public void setFixedLengthStreamingMode(long n/int n)throws IllegalStateException It used to set the length of a content written on the output stream if it knows in advance.
public String getHeaderField() It returns the n header field, or null if it does not exist. It overrides the getHeaderField method of URLConnection class.
public String getResponseMessage() It retrieves the response message.
protected String getRequestMethod() It returns the request method.
protected void setRequestMethod(String method)throws ProtocolException It is used to set the request method. The default is GET.
protected int getResponseCode() To retrieve the response status from the server.

Example 1: To read the header information

import java.io.*;
import java.net.*;
public class httpcon1
{
public static void main(String s[])
{
try
{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
HttpURLConnection h1=(HttpURLConnection)url.openConnection();
for(int i=1;i<=8;i++)
{
System.out.println(h1.getHeaderFieldKey(i)+"="+h1.getHeaderField(i));
}
h1.disconnect();
}catch(Exception e){
System.out.println(e);
}}
} 

The output of the above program:

read the header information

Example 2: To use http accessing webpage.

To access http client resources via the HTTP protocol. The URL class provides the address to a web resource. HttpURLConnection allows to create an InputStream. By using the InputStream, you can use it to read the file.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class httpcon1{
private static final String line = System.getProperty("line.separator");
public static void main(String s1[]) {
try {
URL url = new URL("https://www.google.com/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
String readStream = readStream(con.getInputStream());          
System.out.println(readStream);
} catch (Exception e) {
 e.printStackTrace();
}
}
private static String readStream(InputStream in) {
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in));) {
 String nextLine = "";
while ((nextLine = reader.readLine()) != null) {
sb.append(nextLine +line);
}
} catch (IOException e) {
           e.printStackTrace();
        }
       return sb.toString();
   }
} 

Explanation of the above program:

  • The URL class is used to create the URL object.
  • The openConnection() of the URL is to create an object of the URLConnection, which is typecasted to HttpURLConnection.
  • The StringBuilder in Java represents a mutable sequence of characters. The StringBuilder class differs from the StringBuffer class based on synchronization. It is recommended to use this class in comparison with StringBuilder as it will be faster under most implementations. An instance of StringBuilder is not safe for use by multiple threads.
  • An InputStreamReader changes byte streams to character streams. It reads bytes and converts them into characters. A BufferedReader is a class in Java that reads text from a character-input stream, buffering characters for the reading of lines and arrays. The readLine() method of the BufferedReader class reads a line of text.

The output of the above program:

Explanation of the above program

Example 3: To get the return code from a webpage.

Returns code is a standardized code that is returned by the webserver if some specific situation has occurred.

The commonly used return codes are:

Return code Explanation
200 ok
301 Permanent redirect to another webpage
400 Bad request
404 Not found
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class httpcon1 {
public static void main(String s1[]) throws IOException {
String urltext = "https://www.facebook.com/";
URL url = new URL(urltext);
int responseCode = ((HttpURLConnection) url.openConnection()).getResponseCode();
 System.out.println(responseCode);
}
}

The output of the above:

To get the return code from a webpage.

Example 4: To describe the kind of web resource.

The internet media type(MIME), describes the kind of web resource.

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class httpcon1 {
public static void main(String s1[]) throws IOException {
String urltext = "https://www.facebook.com/";
URL url = new URL(urltext);
String contentType = ((HttpURLConnection) url.openConnection()).getContentType();
System.out.println(contentType);
  }
} 

The output of the program:

describe the kind of web resource

Related Topics

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.

How to uninstall the Java in Ubuntu

We need java on our computers in our daily lives because there are lots of different applications that are developed using the java environment, so we have to install java...

4 minutes read.

Java try catch

Java try catch There can be statements that can cause exceptions, and the exception leads to abnormal termination of the program. To avoid that abnormal termination, those statements that look potent...

4 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Graphics Program in Java

Graphics Program in Java The graphics program in Java is part of the Swing program in Java. In this section, we will learn about the implementation of custom graphics using some...

6 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

String Coding Interview Questions in Java

What is String in Java?In Java, a String is a Class that is defined in the java.lang package. It isn't a basic data type like int or long. Character Strings...

5 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute 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 find characters with the maximum number of times in a string java

Problem statement In this problem, users want to find the maximum count of a character from the string and return the character along with its count. Your task is to create...

3 minutes read.

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These...

5 minutes read.

Array and String with Examples in Java

Array in Java: An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++. Key...

6 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

Kotlin Vs Java

Kotlin Vs Java There are many languages available for Android development. Java is the official language for android development but Kotlin is becoming popular nowadays. This article discusses both of these...

4 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.