HttpURLConnection in Java

HttpURLConnection is the subclass of URLConnection that provides the support for HTTP connections. This class provides the information about header, status code, response etc.

HttpURLConnection Class Methods

Following are some important methods of HttpURLConnection class.

MethodsDescription
String getRequestMethod()Returns a string which tells how URL request are made. The default value is GET.
static boolean getFollowRedirects()Returns ‘true’ if redirects are automatically followed, otherwise ‘false’.
String getResponseMessage()Return the response message associated with response code. It throws IOException, if the connection fails.
Int getResponseCode()Returns the HTTP response code. It returns -1 if response code is not obtained.

Example: Illustrating different methods of URLConnection class

import java.net.*;
import java.io.*;
import java.util.*;
public class HttpURLConnDemo
{
    public static void main(String args[])
    {
        try
        {
            URL url = new URL("http://www.tutorialride.com/java-technologies.htm");
            HttpURLConnection httpurl = (HttpURLConnection) url.openConnection();
            System.out.println("Request Method: "+ httpurl.getRequestMethod());
            System.out.println("Response code: "+ httpurl.getResponseCode());
            System.out.println("Response Message: "+httpurl.getResponseMessage());
        }
        catch(Exception e)
        {
            System.out.println("Exception caught: "+e);
        }
    }
}


Output:
Request Method: GET
Exception caught: java.net.UnknownHostException: www.tutorialride.com