Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Java.net.HttpURLConnection Class in Java
2.1.
HttpURLConnection Class Constructor
2.2.
Java HttpURLConnection Methods
2.3.
How to get the object of HttpURLConnection class
2.4.
Java HttpURLConnection Example
3.
Frequently Asked Questions
4.
Key Takeaways
Last Updated: Mar 27, 2024

Java HttpURL Connection

Author Sanjana Yadav
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Java HttpURL connection class is a popular choice among Java developers for connecting with web servers, and the Android development team has formally recommended using it wherever feasible.

Java.net.HttpURLConnection Class in Java

HttpURLConnection is an abstract class that extends the URLConnection class. It inherits all of the functionality of its parent class, plus HTTP-specific capabilities. It is another class that is used for the more secure HTTPS protocol.

You may obtain information from any HTTP URL using the HttpURLConnection class, such as header information, status code, response code, and so on.

HttpURLConnection Class Constructor

It creates an instance of the HttpURLConnection class.

Syntax

protected HttpURLConnection(URL u)

Parameters : 

u - the URL, Constructs the httpurlconnection to specified URL.

Java HttpURLConnection Methods

Method

Syntax

Description

getResponseCode()

Syntax - protected int getResponseCode()

1xx : Information

2xx : Success

3xx : Redirection

4xx : Client error

5xx : Server error

Used to obtain the server's response status.
setRequestMethod() 

Syntax- protected void setRequestMethod(String method) throws ProtocolException

Parameters- 

method- Must be any one of the following-

GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE

Throws-

ProtocolException - If the method is not valid for http.

This function is used to specify the request method. The default is GET.
getRequestMethod()  Syntax - protected String getRequestMethod() Returns the request method.
getResponseMessage() 

Syntax -  public String getResponseMessage()           

200 - OK

404 - NOT FOUND

Retrieves the response message.
getHeaderField()

Syntax - public String getHeaderField(int n)     

Parameters- 

n - Index of the header field.

The nth header field is returned, or null if it does not exist. It overrides the URLConnection class's getHeaderField function.
setFixedLengthStreamingMode()

Syntax - public void setFixedLengthStreamingMode(long n/int n) throws IllegalStateException

Parameters- 

n - Length of content to be written.

Throws-

IllegalStateException: If the specified length of content is not written on 

the outputstream.

If the length of the material to be written on the outputstream is known ahead of time, this method is used to set it.
setFollowRedirects()

Syntax - public void setFollowRedirects(boolean b)           

Parameters- 

b : Must be true or false.

Sets whether or not 3xx response code queries are automatically routed.
getFollowRedirects() Syntax - public static boolean getFollowRedirects() Returns true or false depending on whether or not automatic redirection is enabled.
disconnect() Syntax- public void disconnect() Indicated that further queries to the server are highly unlikely.
usingProxy()  Syntax - public boolean usingProxy() Returns true if the connection was formed using a proxy, otherwise false.
setChunkedStreamingMode()

Syntax - public void setChunkedStreamingMode(int n) 

      throws IllegalStateException          

Parameters- 

n - length written in each chunk.

Throws-

IllegalStateException- If some different streaming mode is enabled.

When the length of the content is unknown, this mode is used. Instead of producing a fixed-length buffer and writing it to the server, content is divided into chunks and then written. All servers do not support this mode.
getPermission() Syntax - public Permission getPermission() Gets the permissions needed to connect to the target host and port.
getErrorStream()

Syntax - public InputStream getErrorStream()

 

If the server cannot be reached or an error has occurred, this method returns the error stream. It may offer instructions on how to resolve the server problem.
setInstanceFollowRedirects()

Syntax - public void setFollowRedirects(boolean b)           

Parameters- 

b : Must be true or false.

Sets whether this instance of httpURLconnection will automatically redirect 3xx response code requests. It overrides the setFollowRedirects argument, which is more general. If setFollowRedirects is not given, the instance will redirect using setFollowRedirects ().
getInstanceFollowRedirects() Syntax - public boolean getFollowRedirects()  Returns true or false depending on whether automatic instance redirection is enabled or disabled.

Also see, Duck Number in Java and Hashcode Method in Java

How to get the object of HttpURLConnection class

The URL class's openConnection() method returns an object of the URLConnection class.

Syntax:

public URLConnection openConnection()throws IOException{}
As seen below, you may typecast it to HttpURLConnection.
URL url=new URL("https://en.wikipedia.org/wiki/Java_(programming_language)");    
HttpURLConnection huc=(HttpURLConnection)url.openConnection();  

Java HttpURLConnection Example

import java.io.*;    
import java.net.*;    
public class HttpURLConnectionDemo{    
	public static void main(String[] args){    
		try{    
			URL url=new URL("https://en.wikipedia.org/wiki/Java_(programming_language)");    
			HttpURLConnection huc=(HttpURLConnection)url.openConnection();  
			for(int i=1;i<=8;i++){  
			System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));  
		}  
		huc.disconnect();   
		}catch(Exception e){System.out.println(e);}    
	}    
}    

Output

Date = Thu, 17 Feb 2022 03:46:11 GMTVary = Accept-Encoding,Cookie,Authorization
Server = ATS/8.0.8
X-Content-Type-Options = nosniff
P3p = CP="See https://en.wikipedia.org/wiki/Special:CentralAutoLogin/P3P for more info."
Content-Language = en
Last-Modified = Wed, 16 Feb 2022 04:03:18 GMT
Content-Type = text/html; charset=UTF-8


Try it on online java compiler.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

  1. How do I set up HttpURLConnection?
    By default, HttpURLConnection employs the GET technique. If setDoOutput(true) is invoked, it will utilize POST. SetRequestMethod may be used with other HTTP methods (OPTIONS, HEAD, PUT, DELETE, and TRACE) (String).
     
  2. What does openConnection () method return?
    openConnection() returns a java. net object. URLConnection is an abstract class whose subclasses represent different kinds of URL connections. When you connect to an HTTP URL, the openConnection() function returns a HttpURLConnection object.
     
  3. Should I disconnect HttpURLConnection?
    Do not use the HttpURLConnection. disconnect() method. To cache the underlying TCP connection, you must read all of the data in the input stream before closing it.
     
  4. How do I get HttpURLConnection response?
    To obtain the response body as a String from a URL, we must first build a HttpURLConnection with our URL: HttpURLConnection connection = (HttpURLConnection) new URL(DUMMY URL). openConnection();

Key Takeaways

  • Cheers if you reached here! In this blog, we learned about the Java HttpURL connection class.
  • We have covered the basic introduction of this class and how it works.
  • We have also seen its constructor and several methods inside it.
  • Further, we saw an example to get a clear understanding of the topic.


On the other hand, learning never ceases, and there is always more to learn. So, keep learning and keep growing, ninjas!
Check out the Data Structures in Java to get hands-on experience and learn Java from experts.
Good luck with your preparation!

Previous article
Java URL
Next article
Inter Thread Communication in Java
Live masterclass