Java.net.HttpURLConnection Class in Java

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 which is used for the more secured HTTPS protocol.
Where is it used?
It is one of the popular choices among the Java developers for interacting with web servers and android developing team has officially suggested to use it wherever possible.
At the end, this article illustrates a simple implementation of an interactive application which uses microsoft emotion api to retrieve the emotion scores from an image using methods of HttpURLConnection class.

Constructor:

Syntax : protected HttpURLConnection(URL u):
Parameters : 
u - the url
Constructs the httpurlconnection to specified URL.

Methods (other than in URLConnection class):



  1. getResponseCode() : Used to retrieve the response status from server.
    Syntax : protected int getResponseCode()
    1xx : Information
    2xx : Success
    3xx : Redirection
    4xx : Client error
    5xx : Server error
    
  2. setRequestMethod() : Used to set the request method. Default is GET.
    Syntax :  protected void setRequestMethod(String method) 
                                    throws ProtocolException
    Parameters: 
    method : Must be any one of the following-
    GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE
    Throws :
    ProtocolException - If the method is not valid for http.
    
  3. getRequestMethod() : Returns the request method.
    Syntax :  protected String getRequestMethod()           
    
  4. getResponseMessage() :Retrieves the response message.
    Syntax :  public String getResponseMessage()           
    200 - OK
    404 - NOT FOUND
    
  5. getHeaderField() : Returns the nth header field, or null if it does not exist. It overrides getHeaderField method of URLConnection class.
    Syntax :  public String getHeaderField(int n)     
    Parameters: 
    n : Index of the header field.
    
  6. setFixedLengthStreamingMode() : Used to set the length of content written on outputstream if it is known in advance.
    Syntax :  public void setFixedLengthStreamingMode(long n/int n) 
                                           throws IllegalStateException          
    
    Parameters: 
    n : Length of content to be written.
    Throws:
    IllegalStateException : If specified length of content is not written on 
    outputstream.
    
  7. setFollowRedirects() : Sets whether a 3xx response code requests be redirected automatically or not.
    Syntax :  public void setFollowRedirects(boolean b)           
    Parameters: 
    b : Must be true or false.
    
  8. getFollowRedirects() : Returns true or false depending on automatic redirection or not.
    Syntax :  public static boolean getFollowRedirects()           
    
  9. disconnect() : Indicated that requests to server are highly unlikely in future.
    Syntax :  public void disconnect()           
    
  10. usingProxy() : Returns true if connection established using a proxy, else false.
    Syntax :  public boolean usingProxy()           
    
  11. setChunkedStreamingMode() : This mode is used when the content length is not known. Instead of creating a buffer of fixed length and writing it to server, content is broken into chunks and then written. Not all servers support this mode.
    Syntax :  public void setChunkedStreamingMode(int n) 
                                           throws IllegalStateException          
    Parameters: 
    n : length written in each chunk.
    Throws:
    IllegalStateException : If some different streaming mode is enabled.
    
  12. getPermission() : Retrieves the permission required to connect to destination host and port.
    Syntax :  public Permission getPermission()           
    
  13. getErrorStream() : Gets the error stream if the server cannot be connected or some error occured. It can contain information about how to fix the error from server.
    Syntax :  public InputStream getErrorStream()           
    
  14. setInstanceFollowRedirects() : Sets whether a 3xx response code requests be redirected automatically by this instance of httpURLconnection. It overrides the more generic setFollowRedirects
    parameter. If not specified, then the instance redirects based on setFollowRedirects().

    Syntax :  public void setFollowRedirects(boolean b)           
    Parameters: 
    b : Must be true or false.
    
  15. getInstanceFollowRedirects() : Returns true or false depending on automatic instance redirection set or not.
    Syntax :  public boolean getFollowRedirects()           
    
    

Refer to URLConnection article for all methods inherited from it.

Java Implementation:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to illustrate the 
// use of HttpURLConnection
// to retrieve the emotion score 
// of image using Microsoft Emotion api
  
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;
  
public class httpconclass 
{
    public static void main(String args[]) throws IOException 
    {
        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 
            {
  
                // url for microsoft congnitive server.
                URL url = 
                HttpURLConnection con =
                        (HttpURLConnection) url.openConnection();
  
                // set 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);
  
                // set the auto redirection to true
                HttpURLConnection.setFollowRedirects(true);
  
                // override the default value set by
                // the static method setFollowRedirect above
                con.setInstanceFollowRedirects(false);
  
                // set the doOutput to true.
                con.setDoOutput(true);
  
                OutputStream out = con.getOutputStream();
                // System.out.println(ezm.toString().getBytes().length);
  
                // write on the output stream
                out.write(ezm.toString().getBytes());
                InputStream ip = con.getInputStream();
                BufferedReader br1 = 
                        new BufferedReader(new InputStreamReader(ip));
  
                // Print the response code
                // and response message from server.
                System.out.println("Response Code:" 
                                        + con.getResponseCode());
                System.out.println("Response Message:" 
                                    + con.getResponseMessage());
  
                // uncomment the following line to
                // print the status of
                // FollowRedirect property.
                // System.out.println("FollowRedirects:" 
                //              + HttpURLConnection.getFollowRedirects());
  
                // to print the status of 
                // instanceFollowRedirect property.
                System.out.println("InstanceFollowRedirects:" 
                                + con.getInstanceFollowRedirects());
  
                // to print the 1st header field.
                System.out.println("Header field 1:" 
                                    + con.getHeaderField(1));
  
                // to print 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 (Exception e) 
              
            {
                System.out.println(e.getMessage());
            }
  
        }
    }
  
}

chevron_right


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}}]

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. It can be downloaded from sourceforge.com.

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 contentlngth 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

Please refer to this page for detailed explanation of Microsoft emotion api. Whole process can be understood in a nutshell as follows:-

  1. Connecting to the server of microsoft emotion API using the url: https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize .
  2. 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 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.
  3. 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.
  4. Writing to Server:- Once we obtain the outputstream to the server we upload our image to server for processing.
  5. Reading the response from the server: After obtaining an inputstream, we use the bufferedreader to output the results from the server.

Reference: Official Java Documentation

This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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

Improved By : Akanksha_Rai



Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.