Android Retrofit 2.1 HTTP client :
In this example i have divided in to 5 steps :
1. Add gradle dependency
2. Create models for accessing the final data (in this example, the api response json converting to java object this object class is called model )
3. Create interface to define api end point
4. Create a service class for interacting our java code with retrofit.
5. Make the api calls wherever you required
1. Add Gradle dependency (ref: http://square.github.io/retrofit/ )
compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0'
2. Create models
User.java
public class User { public int id; public String name; public String email; public String phone; }
3. Create interface
ApiInterface.java
import java.util.List; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Path; import retrofit2.http.Query; import samples.bm.com.firebaselogin2.models.User; public interface ApiInterface { @GET("get/users") Call<List<User>> getAllUsers(); //List<User> is the response from api @GET("get/user") Call<User> getUser( @Query("id") int id); //using query param (get/user?id=17479666). User is the response from the api //@GET("get/user/{id}") //Call<User> getUser( @Query("id") int id); //using path param (get/user/17479666) @POST("register/user") Call<User> registerUser(@Body User user); @FormUrlEncoded @POST("update/{id}/user") Call<User> updateUser(@Field("name") String name, @Field("phone") String phone, @Path("id") String id); }
expected api response
get/users
[ { "id": 17479666, "name": "name1", "email": "name1@domain.com", "phone": "3435353535434" }, { "id": 17479668, "name": "name3", "email": "name3@domain.com", "phone": "3435353343434" } ]
get/user
{ "id": 17479666, "name": "name1", "email": "name1@domain.com", "phone": "3435353535434" }
4. Create a service class
ApiService.java
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class ApiService { private static ApiInterface service; private static String BASE_URL = "https://api.domain.com/"; //your api domain public static ApiInterface getInstance() { if (service == null) { Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); service = retrofit.create(ApiInterface.class); } return service; } }
5. Make the api calls
Retrofit supports synchronous and asynchronous request execution.
Asynchronous Requests
GET calls
ApiService.getInstance().getAllUsers().enqueue(new Callback<List<User>>() { @Override public void onResponse(Call<List<User>> call, Response<List<User>> response) { //api success List<User> users = response.body(); } @Override public void onFailure(Call<List<User>> call, Throwable t) { Log.e("Apicall", t.getMessage()); } });
GET call with query string/param OR GET call with path string/param
int id=17479666; ApiService.getInstance().getUser(id).enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { //api success User user = response.body(); } @Override public void onFailure(Call<User> call, Throwable t) { Log.e("Apicall", t.getMessage()); } });
Post call
POST call with body param
User user = new User("samoe", "some@ss.com", "234242424"); ApiService.getInstance().registerUser(user).enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { //api success User user = response.body(); } @Override public void onFailure(Call<User> call, Throwable t) { Log.e("Apicall", t.getMessage()); } });
POST call with form encoding
String name = "some name"; String phone = "54686868"; String id="17479666"; ApiService.getInstance().updateUser(name, phone, id).enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { //api success User user = response.body(); } @Override public void onFailure(Call<User> call, Throwable t) { Log.e("Apicall", t.getMessage()); } }); }
Synchronous request
You can also call the apis synchronously.
try { List<User> users = ApiService.getInstance().getAllUsers().execute().body(); } catch (IOException e) { e.printStackTrace(); }
You cannot run this code in main tread you will get exception like ( java.lang.RuntimeException:Unable to start activity ComponentInfo{ …. } android.os.NetworkOnMainThreadException). So better to use synchronous request in services or asyncTask.
How to create AsyncTask : https://wiki.workassis.com/android-asynctask
How to create Service : https://wiki.workassis.com/android-intentservice-example