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 .

    Example)
    drag_handle
     
    URL url=new URL("https://www.onlyjavatech.com/HttpURLConnection-Class-in-Java");    
    HttpURLConnection ob=(HttpURLConnection)url.openConnection()
  • Example of HttpURLConnection

    Example of getting header information of any url.

    Example)
    drag_handle
     import java.io.*;    
    import java.net.*;    
    public class Example{    
    public static void main(String[] args){    
    try{    
    URL url=new URL("https://www.google.co.in");    
    HttpURLConnection ob=(HttpURLConnection)url.openConnection();  
    for(int i=1;i<=9;i++){  
    System.out.println(ob.getHeaderFieldKey(i)+" = "+ob.getHeaderField(i));  
    }  
    ob.disconnect();   
    }catch(Exception e){
    e.printStackTrace();
    ;
    }    
    }    
    }    
    
  • output :

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

    Example)
    drag_handle
     
    import java.io.*;
    import java.net.*;
    import java.util.*;
    
    class Example{
    	public static void main(String[] args) throws Exception {
    		System.out.println("Enter url :");
    		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		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) {
    				System.out.print(y);
    			}
    			System.out.println();
    		}
    	}
    }
    
  • 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.

  • Cookies

    The java.net 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.

What next?

The next topic is Datagrams in java

Share this page