HttpURLConnection Class in java

The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol only.

  HttpURLConnection is a subclass of URLConnection which provides support for HTTP connections.

How to get the object of HttpURLConnection class

We can obtain an HttpURLConnection in the same way by calling openConnection( ) on a URL object, but we must type cast the result to HttpURLConnection .

URL url=new URL("");    
HttpURLConnection ob=(HttpURLConnection)url.openConnection()

Example of HttpURLConnection

Example of getting header information of any url.

public class Example{    
public static void main(String[] args){    
URL url=new URL("");    
HttpURLConnection ob=(HttpURLConnection)url.openConnection();  
for(int i=1;i<=9;i++){  
System.out.println(ob.getHeaderFieldKey(i)+" = "+ob.getHeaderField(i));  
}catch(Exception e){

output :

Program of Printing the header fields of URL using Map Interface of Collection Framework.

import java.util.*;

class Example{
	public static void main(String[] args) throws Exception {
		System.out.println("Enter url :");
		BufferedReader br = new BufferedReader(new InputStreamReader(;
		String str = br.readLine();
		HttpURLConnection con = (HttpURLConnection) new URL(str).openConnection();
		Map<String, List<String>> map = con.getHeaderFields();
		Set<Map.Entry<String, List<String>>> itr = map.entrySet();
		for (Map.Entry<String, List<String>> x : itr) {
			String key = x.getKey();
			List<String> values = x.getValue();
			System.out.print(key + "\t");
			for (String y : values) {

The URI Class

The URI class encapsulates a Uniform Resource Identifier (URI). URIs are similar to URLs.
In fact, URLs constitute a subset of URIs. A URI represents a standard way to identify a resource. A URL also describes how to access the resource.


The package includes classes and interfaces that help manage cookies and can be used to create a stateful (as opposed to stateless) HTTP session. The classes are CookieHandler, CookieManager, and HttpCookie.