1 of 9

RetroFit

A Simple, Powerful, Lightweight, REST client for Android from Square

2 of 9

General Pattern

  1. Model response objects to java objects

JSON is deserialized with Google GSON library. Naming can be overridden with the @SerializedName annotation

3 of 9

General Pattern

2. Create a client interface to define methods

Inline Variables can also be defined as follows:

// Produces a url like "foo/idValue/bar?category=categoryValue".� @GET("foo/{id}/bar")void getWithPathParam(@Name("id") String id, @Name("category") String category, Callback<MyJsonObj> callback);

Async

Sync

void getThings(@Name("param") String param, Callback<List<Thing>> callback);

List<Thing> getThings(@Name("param") String param);

4 of 9

General Pattern

3. Use RestAdapter to build the service client:

MyRestInterface client = mRestAdapter.create(MyRestInterface.class);

Keep in mind that this client object is intended to be a long-lived object. You should not create it for every request. In the RetroFitTwitterClient example, a Singleton is used to manage the client instances. It would be best if these client objects were injected via a dependency injection framework like Dagger.

5 of 9

General Pattern

4. Execute requests on the service client:

List<Tweet> tweets = client.getUserTweets(userName, "1");

6 of 9

Strengths

  • Super easy to use
  • Minimal boilerplate coding
  • Easy to read
  • Easy to make changes
  • Lightweight - no-frills and gets out of the way

7 of 9

Weaknesses

  • Lack of control over URL generation
  • No request caching
  • JSON only

8 of 9

Installation options

  • Check out the source and build the .jar
  • Drop the .jar into your /libs folder
  • Include the following additional jars:
    • gson
    • httpmime
    • javax.inject

OR

  • Install it as a library project. git@github.com:dustin-graham/retrofit.git

9 of 9

Code

https://github.com/dustin-graham/ucad_twitter_retrofit_sample