Java HttpURLConnection class Program

Posted by pandu on Programmers See other posts from Programmers or by pandu
Published on 2012-04-11T18:49:39Z Indexed on 2012/04/11 23:44 UTC
Read the original article Hit count: 390

Filed under:

I am learning java. Here is the sample code of HttpURLConnection class usage in some text book

         import java.net.*;
        import java.io.*;
         import java.util.*;
          class HttpURLDemo
      {

public static void main(String args[]) throws Exception {
    URL hp = new URL("http://www.google.com");
    HttpURLConnection hpCon = (HttpURLConnection) hp.openConnection();
    // Display request method.
    System.out.println("Request method is " +
    hpCon.getRequestMethod());
    // Display response code.
    System.out.println("Response code is " +
    hpCon.getResponseCode());
    // Display response message.
    System.out.println("Response Message is " +
    hpCon.getResponseMessage());
    // Get a list of the header fields and a set
    // of the header keys.
    Map<String, List<String>> hdrMap = hpCon.getHeaderFields();
    Set<String> hdrField = hdrMap.keySet();
    System.out.println("\nHere is the header:");
    // Display all header keys and values.
    for(String k : hdrField) {
    System.out.println("Key: " + k +
    " Value: " + hdrMap.get(k));
    }
    }
    }

Question is

Why hpCon Object is declared in the following way?

       HttpURLConnection hpCon = (HttpURLConnection) hp.openConnection();

instead of declaring like this

     HttpURLConnection hpCon = new HttpURLConnection(); 

Author provided the following explanation. I cant understand

Java provides a subclass of URLConnection that provides support for HTTP connections. This class is called 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. (Of course, you must make sure that you are actually opening an HTTP connection.) Once you have obtained a reference to an HttpURLConnection object, you can use any of the methods inherited from URLConnection

© Programmers or respective owner

Related posts about java