Ever since Android API 9, HttpURLConnection has become the recommended HTTP library for Android applications. During one of my projects I had to learn how to integrate HttpURLConnection into an Android project, so I decided to put it on paper and share it to help others, while discussing some of the caveats that every developer should take into consideration.
I am integrating the HTTP library into a clean, straight out of the Android Studio new project wizard. This tutorial will create 2 HTTP calls, a GET and a POST to a publicly available RESTful API, hosted by reqres.in, a service “that allows us to test our front-end against a real API”.
Starting integrating HttpURLConnection is simple, given that the HTTP library is included in the Android API since API 1. However, we must take into consideration the fact that the library is not prepared for native asynchronous calls, requiring us to make use of workers, such as AsyncTasks, to perform HTTP network calls outside the main UI thread.
First, add the permission to the application’s manifest to allow the application to access the Internet:
Now let’s create an AsyncTask to perform an HTTP GET call:
If you are familiar with Android development, this class is pretty straightforward. The main logic of the worker is located inside the doInBackground method. First, I set the desired URL, followed establishing an HTTP connection, via the openConnection method. After checking if the connection was successful, I read the connection’s data from a BufferedReader, in this case, reading it, line by line. And that’s it!
To call this HTTP GET worker, just start the AsyncTask, for instance on the onCreate method of the main activity:
To perform a POST call, just create the following AsyncTask:
The first thing I do is create JSON data to post to the service. To create JSON data, we need to include the gradle dependency:
Then create the URL of the post to be performed, followed by establishing the HTTP connection. Next, I set the HttpURLConnection options to perform the POST and write the JSON data into the connection. Finally, I just check if the post was successfully received by the server and check the server's reply. Again, simple!
As previously, to run this worker, just call it from anywhere in your project, via:
Full project code and final thoughts
The full code used is available at Github. Fill free to adapt the code according to your specific needs.
I hope I helped you in integrating HttpURLConnection into an Android project to perform GET and POST calls, and how to properly used it outside the main UI thread, via an AsyncTask. HttpURLConnection is a mature HTTP library that can be integrated with relative ease. However, I have to say that I prefer approaches like the more modern OkHTTP library. It provides native asynchronous methods, significantly simplifying it integration in a project. Here you can find out more about the Android HTTP Libraries current landscape.