«Back to Home

Core Java

Topics

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.
  1. URL u=new URL("http://www.google.com/images");  
  2. HttpURLConnection h=(HttpURLConnection)u.openConnection();  
Let’s see an example of HttpURLConnection class, given below.
 
Code
  1. import java.io.*;  
  2. import java.net.*;  
  3. public class HttpUrlConnectionClass {  
  4.     public static void main(String[] args) {  
  5.         try {  
  6.             URL u = new URL("http://www.google.com/images");  
  7.             HttpURLConnection h = (HttpURLConnection) u.openConnection();  
  8.             for (int i = 1; i <= 10; i++) {  
  9.                 System.out.println(h.getHeaderFieldKey(i) + " = " + h.getHeaderField(i));  
  10.             }  
  11.             h.disconnect();  
  12.         } catch (Exception e) {  
  13.             System.out.println(e);  
  14.         }  
  15.     }  
  16. }  
9

Output

10

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.