Tag Archives: HTTP

Introduction to Android HTTP communication with Retrofit

In a previous post I described how to implement HTTP requests using the Google’s library Volley. We saw how to save lot of boilerplate code in such a critical part of our apps like the networking communication with our server using a well tested and reliable library.

We showed how straightforward is to have so useful features like parallel HTTP requests, cancel petitions, image downloads caching, etc.

But Volley is not our only option, there are more libraries out there that does a really good job,  and one of the well known and widely used is Retrofit from the Square people.  In this post you can find a very good comparison  between the two libraries where Retrofit would win as it is faster that Volley, but you better try and test by yourself and check which one would fit better on your project.

You can find here in my AndroidBootstrap project in Github how to integrate the library in an Android Studio project and a few examples of use.

 

Integration in our project

You can download the library .jar from here or if you’re using Maven:

<dependency>
 <groupId>com.squareup.okhttp</groupId>
 <artifactId>okhttp</artifactId>
 <version>2.0.0</version>
</dependency>
<dependency>
 <groupId>com.squareup.okhttp</groupId>
 <artifactId>okhttp-urlconnection</artifactId>
 <version>2.0.0</version>
</dependency>

Or if using Gradle:

compile 'com.squareup.retrofit:retrofit:1.9.0'

 

Retrofit client

The first thing we need to do is to initialise the Retrofit rest client object. You might want to use a singleton to manage the life cycle of the client if you’re planning to do frequent request on your app:

public class RestClient {

    private static final String API_URL = "http://jsonplaceholder.typicode.com";

    private static RestApi mRestApi = null;

    public static synchronized RestApi getInstance() {

        if(mRestApi == null) {

            RestAdapter adapter = new RestAdapter.Builder()
                    .setEndpoint(API_URL)
                    .build();

            mRestApi = adapter.create(RestApi.class);
        }

        return mRestApi;
    }
}

 

A simple HTTP GET request

Retrofit uses Java interfaces and annotations to define the REST API requests. Then it will generate the necessary code thto perform the HTTP requests and finally will convert the Json response in the specific pojo object using Gson.

Let’s take a look to this example:

@GET("/comments")
void getCommentsAsync(@Query("postId") String postNumber, Callback<list> callback);

As you can see “@GET” specifies the type of request and “/comments” is the path of the request.

Then we have the “@Query” annotation that specifies the addition of a param to the url which will take the value of the param “postNumber”.

Finally we can see the Callback parameter where retrofit will retrieve the object that has been created from the Json response using the Gson library.

In case we need to do a synchronous request the interface will look like this:

@GET("/comments")
List getCommentsSync(@Query("postId") String postNumber);

If we need to perform a POST operation:

@POST("/comments")
void postComment(@Body CommentItem item, Callback cb);

And if we need to add headers to our request:

@Headers("Cache-Control: max-age=640000")
@GET("/comments")
List getCommentsWithCustomHeader();

 

So this is a very brief introduction to the Retrofit library. As mentioned before you can find examples of the use and integration in my Bootstrap Android project. I’ll be adding more examples of useful libraries or snippets in the future.

And finally if you have any comment or suggestion please don’t hesitate in leave it below!

Advertisements
Tagged , , ,

HTTP networking on Android using Volley

One of the most common functionalities that as Android developers we need to implement is the network communication. Almost all apps at some point needs to get some kind of data from a server, web service, etc.

We could implement our own classes using for example the Java HttpURLConnection, but as pragmatic, productive and lazy developers we should always try to don’t reinvent the wheel and find some reliable and well tested library.

Two of the best and more used options are Retrofit from the Square people and Volley from Google, which I’m going to focus in this post and I will leave Retrofit for another post.

 

What is Volley?

Volley is a library created by Google that offers out of the box a set of very cool features, amongst others :

  • Concurrent connections.
  • Automatic requests scheduling and cancelation.
  • Memory and disk response caching.

Here you can find a good talk at the 2013 Google I/O conference from Ficus Kirkpatrick:

 

Integration in our project

So, let’s see how to use it. First thing we have to clone the project from Git:
https://android.googlesource.com/platform/frameworks/volley

and then import it in our project or make a .jar and include it as a library.

Probably our app will be making requests in different activities quite often so the most optimum way to manage the life of our Volley object is implementing a Singleton class and create the instance it on the Application class instead or creating a new object on each activity. This singleton is going to contain the RequestQueue object that will manage the requests concurrency. Something like this:

    private static VolleyManager mInstance = null;
    private static Context mContext;
    private RequestQueue mRequestQueue;

    private VolleyManager(Context context) {
        mContext = context;
        mRequestQueue = getRequestQueue();
    }

    public static synchronized VolleyManager getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new VolleyManager(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

 

HTTP GET

Now we are going to implement a simple HTTP GET request that will retrieve a Json object. Volley offers four types of requests responses: “StringRequest”, “ImageRequest”, “JsonObjectRequest” and finally the ability to implement our custom request.

In this example we will be using a JsonObjectRequest. It’s based on real code from our public transport app BilbaoMoves, where we are calling to our server to get the real time arrivals of a specific transport stop. I just changed the endpoint url and the classes names.

It looks like this:

	JsonObjectRequest jsObjRequest =
        new JsonObjectRequest(Request.Method.GET, "http://urlToAnAwesomeEndpoint/webservice/",
                null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject jsonObject) {

				Gson gson = new Gson();

                MyExampleClass myExample =
                    gson.fromJson(jsonObject.toString(), MyExampleClass.class);

				//	Do something awesome here with myExample object
				//	.......

           }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            	//	The request failed  😦
            }
        });

        // Access the RequestQueue through the singleton class.
        mVolleyMng.addToRequestQueue(jsObjRequest);

 

HTTP POST

Creating a HTTP POST and send parameters in the request is quite straightforward as you can see in this example:

ExampleClass exampleObj = new ExampleClass();
exampleObj.setName("David");
exampleObj.setSurname("Guerrero");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(exampleObj),
     new Response.Listener<JSONObject>() {
         @Override
         public void onResponse(JSONObject response) {
             try {
                  //   Everything went OK
             } catch (JSONException e) {
                 e.printStackTrace();
             }
         }
     }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError error) {
              //   Hmmm... Something went wrong
         }
 });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

</pre>
<pre>

 

Cancel a Request

Sometimes we will need to cancel a request, for example when the user close the app or change to a different activity where we don’t need any more the data provided by the request. We could place the cancel request code in the onStop event of our activity, something like this:


@Override
protected void onStop () {
    super.onStop();
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(TAG);
    }
}

 

And that’s all. This is a basic introduction to how to make basic requests, but Volley offer another really interesting and useful features like caching and image loader (eg. to populate a list view with images asynchronously), but that will be material for another post. Until then, please all comments, suggestions and questions are very welcome!

 

Tagged , ,