Recently in one of my Android projects, I used a library called Retrofit which is “a type-safe REST client for Android and Java”.
It is a small library and deceptively simple to use but has the potential to save you from writing a lot of [boilerplate] code.
When developing an app, sooner or later you are going to want to make contact with the outside world to fetch some data or information.
Whether you are looking for the current weather, the latest stock price or a twitter feed there will normally be a web service that you can connect with.
A common approach for web service providers is to create RESTful APIs. These are published at a base URI and use standard HTTP methods (like GET, PUT, POST or DELETE) for receiving and sending data.
In the past I would have probably created something like this pseudocode:
URL connectionURL = new URL(“https://api.github.com/users/brightec/repos”); HttpURLConnection urlConnection = (HttpURLConnection) connectionURL.openConnection(); urlConnection.setRequestMethod(“GET”); int status = urlConnection.getResponseCode(); if (status != 200) { // Do some error handling! return; }
InputStream in = new BufferedInputStream(urlConnection.getInputStream()); InputStreamReader reader = new InputStreamReader(in); BufferedReader bufferedReader = new BufferedReader(reader); StringBuilder builder = new StringBuilder(); String line = bufferedReader.readLine(); while (line != null) { builder.append(line); line = bufferedReader.readLine(); } String httpResponse = builder.toString();
JsonObject jsonResponse = new JsonParser().parse(httpResponse).getAsJsonObject(); Gson gson = GsonBuilder().create; Repo[] repos = gson.fromJson(jsonResponse, Repo[].class);
Fortunately, there is an easier way. In three simple steps follow the Retrofit way:
public interface GitHubService { @GET("/users/{user}/repos") List listRepos(@Path("user") String user); }
RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint("https://api.github.com") .build(); GitHubService service = restAdapter.create(GitHubService.class);
List repos = service.listRepos("brightec");
Using Retrofit, most of the heavy lifting is done for you. Most excitingly, this is just the beginning of what it can do.
Visit http://square.github.io/retrofit for further info.
Search over 400 blog posts from our team
Subscribe to our monthly digest of blogs to stay in the loop and come with us on our journey to make things better!