Android HttpURLConnection Example

Connecting Android application to a remote server is the most common task in the android application development. Android HttpURLConnection client is the preferred method to connect to a remote server through HTTP. All the network calls use the HTTP to send and receive data.

We will create a sample project to demonstrate how HttpURLConnection in android works..

Android HttpURLConnection client supports TLS, streaming uploads and downloads, configurable timeouts, IPv6, and connection pooling.

Read more on Android Official Website

Android HttpURLConnection Methods

We have these public methods in HttpURLConnection class. A brief description is given below, for each method.

void disconnect ()
disconnect method closes the connection when all response data has been read.

InputStream getErrorStream ()
It is used to read error response if HTTP response returns any error.

boolean getFollowRedirects ()
getFollowRedirects methods return a boolean type value which indicates whether or not HTTP redirects should be automatically followed.

String getHeaderField (int n)
This method returns the header field based on given index.

long getHeaderFieldDate (String name, long Default)
It returns the long type value of the named field parsed as a date.

String getHeaderFieldKey (int n)
Returns the key for the header field based on passed index.

boolean getInstanceFollowRedirects ()
If it returns true which means protocol will automatically follow redirects. In the case of false, the protocol will not automatically follow redirects.

Permission getPermission ()
getPermission method returns a SocketPermission object which represents the permission required to connect to the destination host and port.

String getRequestMethod ()
It is used to get the request method. It returns HTTP request method

int getResponseCode ()
It returns integer value. It is used to get the status code from an HTTP response message. It will return either Http status code or -1 in the case of an error. Following are the available response codes.

HTTP Response Codes:

202: Accepted.
502: Bad Gateway.
405: Method Not Allowed.
400: Bad Request.
408: Request Time-Out.
409: Conflict.
201: Created.
413: Request Entity Too Large.
403: Forbidden.
504: Gateway Timeout.
410: Gone.
500: Internal Server Error.
411: Length Required.
301: Moved Permanently.
302: Temporary Redirect.
300: Multiple Choices.
406: Not Acceptable.
203: Non-Authoritative Information.
404: Not Found.
501: Not Implemented.
304: Not Modified.
204: No Content.
200: OK.
206: Partial Content.
402: Payment Required.
412: Precondition Failed.
407: Proxy Authentication Required.
414: Request-URI Too Large.
205: Reset Content.
303: See Other.
401: Unauthorized.
503: Service Unavailable.
415: Unsupported Media Type.
305: Use Proxy.
505: HTTP Version Not Supported.

String getResponseMessage ()
It returns the string. It is used to get the HTTP response message if there is any message return from the server along with HTTP response code.

void setChunkedStreamingMode (int chunklen)
This method is used to enable streaming of an HTTP request body without internal buffering when the content length is not known in advance. It should be called before the connection is connected.

void setFixedLengthStreamingMode (int contentLength)
It enables the streaming of an HTTP request body without internal buffering when the content length is known in advance. An error will occur if the application writes more data than specified in content length. An error will also occur if output stream is closed before writing the specified amount of content. It should be called before URLConnection is connected.

void setFixedLengthStreamingMode (long contentLength)
It allows enabling streaming of an HTTP request body without internal buffering when the content length is known in advance.An error will occur if an application writes more data than specified in content length. An error will also occur if output stream is closed before writing the specified amount of content. It should be called before URLConnection is connected.

void setFollowRedirects (boolean set)
If a server returns 301 or 302 to response if a request is redirected from original URL to another URL. This method is used to set whether redirect should be followed automatically or not. It is set to true by default.We can get the redirect URL by calling getHeaderField(‘Location’);

void setInstanceFollowRedirects (boolean followRedirects)
Sometimes server redirects the request from one URL to another URL and returns 301 or 302 response code on a server. This method is used to sets whether HTTP redirects should be followed automatically or not by this HttpURLConnection instance.

void setRequestMethod (String method)
It is used to set the method for a request. Available methods are GET, POST, HEAD, OPTIONS, PUT, DELETE and TRACE.

boolean usingProxy()
This method reveals whether the connection is going through a proxy or not.

Using HttpURLConnection Post and Get Method

We will create the sample project in order to implement HttpURLConnection class in our project. We will use Get and Post methods in this example.

Download Source Code
Step:1
Create a new Project in Android Studio with default settings and name it HttpExample.

Step:2
We need Internet permission for performing networks operations. Add Internet permission in AndroidMenifest file.

Step:3
Adding a TextView and Two Buttons in activity layout file. We will display the response from the server into TextView. Buttons will be used to send Post and Get request. Below is the code of main activity layout file.

activity_main.xml

Step:4
Modify your main activity file as per below code. We have used HttpURLConnection class within AsyncTask to perform network operations on a separate thread without blocking UI.

MainActivity.java

In the onCreate method, we have initialized the UI elements TextView and Buttons. Added onClickListener for both buttons.

HttpURLConnection Get Request

ByGetMethod will send the get HTTP request to the remote server. It will return the response from the server in the InputStream format.

HttpURLConnection Post Request

ByPostMethod will send the post HTTP request to the remote server. It will return the response from the server in the InputStream format.

Converting InputSteam into String

ConvertStreamToString() method will accept InputStream and convert it into string format. This method will return a string.

Using HttpURLConnection within AsyncTask

We have create a AsyncTask class MakeNetworkCall. It will call the ByPostMethod and ByGetMethod on background thread without blocking the main thread. we are also updating TextView in onPreExecute and onPostExecute.

We have a php file on the server to communicate with our android application. Android application is ending HTTP post and Get request to http.php. Below is the code of http.php
http.php

Finally, Application is ready, Running the application will generate following outputs for Get and Post method respectively.

android httpurlconnection get android httpurlconnection post

Android HttpURLConnection Example – Video Demo

This video is showing the project structure in Android Studio and application output on an emulator.

Android HttpURLConnection – More Examples

I hope you will like this tutorial on Android httpURLConnection. Subscribe to our Newsletter to get new articles and tutorials in your inbox as soon as they published. You can connect with us on Facebook and also subscribe to our Youtube Channel.

Check Also

asynctask kotlin example

Kotlin AsyncTask Tutorial with Example

Here is an example of implementing AsyncTask in Kotlin. I will create an Android application …