HttpURLConnection Class In Java
HttpURLConnection Class
In Java, The HttpURLConnection class is http particular URLConnection and it works for HTTP protocol only. With the help of HttpURLConnection class, we can get information of any HTTP URL such as a header information, response code, status code etc.
The java.net.HttpURLConnection is child class of URLConnection class.
Get the object of HttpURLConnection class
The URL class openConnection() method is used to return the object of URLConnection class.
Syntax
public URLConnection openConnection()throws IOException{}
We can classify it to HttpURLConnection type, as given below.
- URL u=new URL("http://www.google.com/images");
- HttpURLConnection h=(HttpURLConnection)u.openConnection();
Let’s see an example of HttpURLConnection class, given below.
Code
- import java.io.*;
- import java.net.*;
- public class HttpUrlConnectionClass {
- public static void main(String[] args) {
- try {
- URL u = new URL("http://www.google.com/images");
- HttpURLConnection h = (HttpURLConnection) u.openConnection();
- for (int i = 1; i <= 10; i++) {
- System.out.println(h.getHeaderFieldKey(i) + " = " + h.getHeaderField(i));
- }
- h.disconnect();
- } catch (Exception e) {
- System.out.println(e);
- }
- }
- }
Output
Summary
Thus, we learnt that Java HttpURLConnection class is http particular URLConnection and It works for HTTP protocol only. We also learnt how we can use it in Java.