Class in Java

Course Curriculum Class in Java 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.


Syntax : protected HttpURLConnection(URL u):
Parameters :
u - the url
Constructs the httpurlconnection to specified URL.
Methods (other than in URLConnection class):

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
setRequestMethod() : Used to set the request method. Default is GET.
Syntax : protected void setRequestMethod(String method)
throws ProtocolException
method : Must be any one of the following-
Throws :
ProtocolException - If the method is not valid for http.
getRequestMethod() : Returns the request method.
Syntax : protected String getRequestMethod()
getResponseMessage() :Retrieves the response message.
Syntax : public String getResponseMessage()
200 - OK
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)
n : Index of the header field.
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

n : Length of content to be written.
IllegalStateException : If specified length of content is not written on
setFollowRedirects() : Sets whether a 3xx response code requests be redirected automatically or not.
Syntax : public void setFollowRedirects(boolean b)
b : Must be true or false.
getFollowRedirects() : Returns true or false depending on automatic redirection or not.
Syntax : public static boolean getFollowRedirects()
disconnect() : Indicated that requests to server are highly unlikely in future.
Syntax : public void disconnect()
usingProxy() : Returns true if connection established using a proxy, else false.
Syntax : public boolean usingProxy()
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
n : length written in each chunk.
IllegalStateException : If some different streaming mode is enabled.

getPermission() : Retrieves the permission required to connect to destination host and port.
Syntax : public Permission getPermission()
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()
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)
b : Must be true or false.
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:

// Java program to illustrate the
// use of HttpURLConnection
// to retrieve the emotion score
// of image using Microsoft Emotion api

import org.json.simple.JSONObject;

public class httpconclass
public static void main(String args[]) throws IOException
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);

// url for microsoft congnitive server.
URL url =
new URL("");
HttpURLConnection con =
(HttpURLConnection) url.openConnection();

// set the request method and properties.
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.

// set the auto redirection to true

// override the default value set by
// the static method setFollowRedirect above

// set the doOutput to true.

OutputStream out = con.getOutputStream();
// System.out.println(ezm.toString().getBytes().length);

// write on the output stream
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.
+ 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)
String xx = response.toString();

} catch (Exception e)



Result :

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

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


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

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

Connecting to the server of microsoft emotion API using the 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 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 server for processing.
    Reading the response from the server: After obtaining an inputstream, we use the bufferedreader to output the results from the server.
(Next Lesson) How to start learning Java
', { 'anonymize_ip': true });