Skip to content
Related Articles

Related Articles

Java.net.HttpURLConnection Class in Java

View Discussion
Improve Article
Save Article
  • Last Updated : 20 Apr, 2022

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.

Constructor

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

Methods (Other than in URLConnection class)

MethodAction 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 

https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize

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.

Implementation: 

Java




// Java Program to Illustrate Use
// of HttpURLConnection Class
// to Retrieve Emotion score of Image
// Using Microsoft Emotion API
 
// Importing required classes
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
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(System.in));
        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(
                    "https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize");
                HttpURLConnection con
                    = (HttpURLConnection)
                          url.openConnection();
 
                // Setting the request method and
                // properties.
                con.setRequestMethod("POST");
                con.setRequestProperty(
                    "Ocp-Apim-Subscription-Key", key);
                con.setRequestProperty("Content-Type",
                                       "application/json");
                con.setRequestProperty("Accept",
                                       "application/json");
 
                // 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.
                con.setFixedLengthStreamingMode(83);
 
                // Setting the auto redirection to true
                HttpURLConnection.setFollowRedirects(true);
 
                // Overriding the default value set by
                // the static method setFollowRedirect above
                con.setInstanceFollowRedirects(false);
 
                // Setting the doOutput to true for now
                con.setDoOutput(true);
 
                OutputStream out = con.getOutputStream();
                // System.out.println(ezm.toString().getBytes().length);
 
                // Writing on the output stream
                out.write(ezm.toString().getBytes());
                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());
                System.out.println(
                    "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
                System.out.println(
                    "InstanceFollowRedirects:"
                    + 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) {
                    response.append(responseSingle);
                }
                String xx = response.toString();
                System.out.println(xx);
            }
 
            // Catch block to handle exceptions
            catch (Exception e) {
               
                // Display exception/s on console
                System.out.println(e.getMessage());
            }
        }
    }
}

Output: 

Response Code:200
Response Message:OK
FollowRedirects:true
InstanceFollowRedirects:false
Header field 1:no-cache
Using proxy:false
[{"faceRectangle":{"height":134,"left":62,"top":86,"width":134},"scores":{"anger":4.105452E-
14,"contempt":1.240792E-11,"disgust":2.58925052E-11,"fear":1.82401266E-17,"happiness":1.0,
"neutral":2.487733E-10,"sadness":6.02089044E-14,"surprise":2.665974E-12}}]

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: https://media.geeksforgeeks.org/wp-content/uploads/Brad_Pitt.jpg

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.

This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!