Open In App Class in Java

Last Updated : 20 Apr, 2022
Like Article

HttpURLConnection class is an abstract class directly extending from URLConnection class. It includes all the functionality of its parent class with additional HTTP-specific features. HttpsURLConnection is another class that is used for the more secured HTTPS protocol. 

It is one of the popular choices among Java developers for interacting with web servers and the android developing team has officially suggested using it wherever possible. Later we will be illustrating a simple implementation of an interactive application that uses Microsoft emotion API to retrieve the emotion scores from an image using methods of HttpURLConnection class.


  • HttpURLConnection(URL u): Constructs the httpurlconnection to specified URL

Methods (Other than in URLConnection class)

Method Action performed
disconnect() Indicated that requests to the server are highly unlikely in the future. 
getErrorStream() Gets the error stream if the server cannot be connected or some error occurred. It can contain information about how to fix the error from the server.
getFollowRedirects() Returns true or false depending on automatic redirection or not.
getHeaderField() Returns the nth header field, or null if it does not exist. It overrides the getHeaderField method of URLConnection class.
getInstanceFollowRedirects() Returns true or false depending on whether automatic instance redirection is set or not.
getPermission() Retrieves the permission required to connect to a destination host and port.
getResponseCode() Used to retrieve the response status from server.
getResponseMessage() Retrieves the response message.
getRequestMethod() Returns the request method.
setInstanceFollowRedirects() Sets whether response code requests be redirected automatically by this instance of HTTP URL connection. It overrides the more generic setFollowRedirects()
setRequestMethod() Used to set the request method. Default is GET
setFixedLengthStreamingMode() Used to set the length of content written on outputstream if it is known in advance.
setFollowRedirects() Sets whether a 3xx response code request be redirected automatically or not.
setChunkedStreamingMode() Used when the content length is not known. Instead of creating a buffer of fixed length and writing it to a server, content is broken into chunks and then written. Not all servers support this mode. 
usingProxy() Returns true if connection is established using a proxy, else false

Tip: It would be good to have understanding of how to read URL using this HttpURLConnection class for better understanding of below implementation.

Illustration: The whole process can be understood in a nutshell as follows: 

Connecting to the server of Microsoft emotion API using the below URL

Setting the properties and methods for firing the request: In this step, we set the methods and properties of our request object. First, we set the method as a request method to be invoked as POST. We also set the User-Agent property to ensure that our request is not blocked by the server because of an unexpected response type which otherwise would work fine on any web browser.

Firing the http get request: After we have created the URL and have created a HttpURLConnection object, we have to actually fire a request. It can explicitly be done by connect() method. It is rather implicitly done whenever we try to use any response message such as getOutputStream() etc.

Writing to Server: Once we obtain the outputstream to the server we upload our image to the server for processing.

Reading the response from the server: After obtaining an inputstream, we use the bufferedreader to output the results from the server.



// Java Program to Illustrate Use
// of HttpURLConnection Class
// to Retrieve Emotion score of Image
// Using Microsoft Emotion API
// Importing required classes
import org.json.simple.JSONObject;
// Main class
// httpconclass class
public class GFG {
    // Main driver method
    public static void main(String args[])
        throws IOException
        // Reading input via BufferedReader class
        BufferedReader br = new BufferedReader(
            new InputStreamReader(;
        int n = Integer.parseInt(br.readLine());
        String key = "833921b016964f95905442e0fab0c229";
        JSONObject ezm;
        while (n-- > 0) {
            String image = br.readLine();
            ezm = new JSONObject();
            ezm.put("url", image);
            // Try block to check for exceptions
            try {
                // URL for microsoft cognitive server.
                URL url = new URL(
                HttpURLConnection con
                    = (HttpURLConnection)
                // Setting the request method and
                // properties.
                    "Ocp-Apim-Subscription-Key", key);
                // As we know the length of our content,
                // the following function sets the fixed
                // streaming mode length 83 bytes. If
                // content length not known, comment the
                // below line.
                // Setting the auto redirection to true
                // Overriding the default value set by
                // the static method setFollowRedirect above
                // Setting the doOutput to true for now
                OutputStream out = con.getOutputStream();
                // System.out.println(ezm.toString().getBytes().length);
                // Writing on the output stream
                InputStream ip = con.getInputStream();
                BufferedReader br1 = new BufferedReader(
                    new InputStreamReader(ip));
                // Printing the response code
                // and response message from server.
                System.out.println("Response Code:"
                                   + con.getResponseCode());
                    "Response Message:"
                    + con.getResponseMessage());
                // Note: Uncomment the following line to
                // print the status of FollowRedirect
                // property
                // System.out.println("FollowRedirects:"
                //           +
                //           HttpURLConnection.getFollowRedirects());
                // Printing the status of
                // instanceFollowRedirect property
                    + con.getInstanceFollowRedirects());
                // Printing the 1st header field
                System.out.println("Header field 1:"
                                   + con.getHeaderField(1));
                // Printing if usingProxy flag set or not
                System.out.println("Using proxy:"
                                   + con.usingProxy());
                StringBuilder response
                    = new StringBuilder();
                String responseSingle = null;
                while ((responseSingle = br1.readLine())
                       != null) {
                String xx = response.toString();
            // Catch block to handle exceptions
            catch (Exception e) {
                // Display exception/s on console


Response Code:200
Response Message:OK
Header field 1:no-cache
Using proxy:false

Output Explanation: To test this program, one should provide the number of images to process and then provide the URL of the images. You can leave the content length property unset as the server would handle it automatically, but if you know the length, modify it each time accordingly. In the given source code, as the content length is set to 83 bytes, a URL of that size should be used. 

Sample URL:

Note: As it is an interactive application, it is advised to run it on offline platforms. JSON library should also be included in the build path of the project to run this application.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads