HttpURLConnection Class in Java


Java provides a subclass of URLConnection that provides support for HTTP connections. This class is called a HttpURLConnection. You obtain an HttpURLConnection in the same way just shown, by calling openConnection() on a URL object, but you must cast the result to HttpURLConnection. Once you have obtained a reference to an HttpURLConnection object, you can use any of the methods inherited from URLConnection.

HttpURLConnection Methods:

static boolean getFollowRedirects(): Returns true if redirects are automatically followed and false otherwise. This feature is on by default.

String getRequestMethod(): Returns a string representing how URL requests are made. The default is GET. Other options, such as POST,
are available.

int getResponseCode() throws IOException: Returns the HTTP response code. –1 is returned if no response code can be obtained. An IOException is thrown if the connection fails.

String getResponseMessage() throws IOException: Returns the response message associated with the response code. Returns null if no message is available. An IOException is thrown if the connection fails.

static void setFollowRedirects(boolean how): If how is true, then redirects are automatically followed. If how is false, redirects are not automatically followed. By default, redirects are automatically followed.

void setRequestMethod(String how) throws ProtocolException: Sets the method by which HTTP requests are made to that specified by how. The default method is GET, but other options, such as POST, are available.

Demonstrate HttpURLConnection Program:

import java.util.*;
class Demo
public static void main(String args[]) throws Exception
URL hp = new URL("");
HttpURLConnection hpCon = (HttpURLConnection) hp.openConnection();
System.out.println("Request method is " + hpCon.getRequestMethod());
System.out.println("Response code is " + hpCon.getResponseCode());
System.out.println("Response Message is " + hpCon.getResponseMessage());
Map<String, List> hdrMap = hpCon.getHeaderFields();
Set hdrField = hdrMap.keySet();
System.out.println("\nHere is the header:");
for(String k : hdrField)
System.out.println("Key: " + k + " Value: " + hdrMap.get(k));