This tutorial explains the usage of the Retrofit library as REST client.
- What is Retrofit?
Retrofit is a REST Client for Android and Java by Square. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice. - Using Retrofit
To work with Retrofit you need basically three classes. - Model class which is used to map the JSON data to
- Interfaces which defines the possible HTTP operations
- Retrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL end point for the HTTP operation.
Every method of an interface represents one possible API call. It must have a HTTP annotation (GET, POST, etc.) to specify the request type and the relative URL. The return value wraps the response in a Call object with the type of the expected result.
Add these two lines to the build.gradle file:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
Also Add Internet permission to AndroidManifest.xml file
Retrofit turns your HTTP API into a Java interface.
<uses-permission
android:name="android.permission.INTERNET" />
Retrofit turns your HTTP API into a Java interface.
public interface ApiClientListener {@FormUrlEncoded@POST("/login/") Call<Login> login(@Field("email") String email, @Field("password") String password); }The Retrofit class generates an implementation of the interface.Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); Calling login APIApiClientListener apiClientListener = retrofit.create(ApiClientListener.class);Call<Login> call = apiClientListener.login("email", "password");call.enqueue(new Callback<Login>() { @Override public void onResponse(Call<Login> call, Response<Login> response) { // Success } @Override public void onFailure(Call<Login> call, Throwable t) { // Error } }); }
Comments
Post a Comment