Search code examples
androidretrofit

Using Retrofit 2.0 in Android


As I am very new to using third-party HTTP libraries for Android like Retrofit, there are a few questions I would like to ask you who could help me.

It seems there recently has been a great change on a transition from Retrofit 1.9 to 2.0, for example the changes on APIs. So I could not find a proper documentations for using the library, even on its own webpage.

When it comes to implementing an HTTP request for registering a user on the server, it seems, according to the webpage, the first thing is to create an interface that defines the role (e.g. POST, GET, etc.). For example:

public interface GitHubService {
  @GET("/users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

And it seems I should create a Retrofit instance to connect to the server and use

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

The things I really would like to find out are,

  1. What does Repo in the above generics mean? that's the first thing I still cannot figure out.

  2. What should be written in the parenthesis followed by each annotation like @POST or @GET? Does it mean a subdirectory under the server URL? According to the example codes above, does the @GET annotation state that the listRepos method get the user value from the 'user' path or something? This is so confusing..

Please, I'm really new to this world, so I'm desperate for your helps. Thanks in advance.


Solution

    1. 'Repo' in this example means a repository on Github. Retrofit automatically deserializes JSON responses to Java POJOs. The example fetches information about Github repositories from the Github API, the fetched repository information is represented by a Repo class / a List of Repo objects. You'll have to provide your own class representation of the data that you're getting from your server / API.
    2. Does it mean a subdirectory under the server URL?

    Basically, yeah. It's the path / Uri to the resource you're trying to access on the server specified with baseUrl.

    In this case we have the baseUrl https://api.github.com. We append the path /users/{user}/repos. The method

    @GET("/users/{user}/repos")
          Call<List<Repo>> listRepos(@Path("user") String user);
    

    takes a user id as an argument and replaces {user} with that argument.

    So if you call that method with the argument JakeWharton the full Uri is

    https://api.github.com/users/JakeWharton/repos
    

    You can call it from your browser to see the response. You'll have to change those Url/Uri Strings to match the API you want to access.

    .