Want create site? Find Free WordPress Themes and plugins.

In this tutorial, I will show you how to use the retrofit 2 library.

 

1-Android Studio and create a new project.

2-Declare the following dependencies in your build.gradle

// Retrofit
compile 'com.squareup.retrofit2:retrofit:2.1.0'
// JSON Parsing
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

3-Include the Internet permission in the application.

<uses-permission android:name="android.permission.INTERNET" />

4-Create models automatically from our JSON response data using jsonschema2pojo.

{

"title": "foo",

"body": "bar",

"userId": 1,

"id": 101

}

In jsonschema2pojo Select source type of JSON, annotation style of Gson, uncheck Allow additional properties, and change the class name and click on preview.

preview

sss

The @serilizeName annotation is needed for Gson to map the JSON keys with our fields. In keeping with Java’s camelCase naming convention for class member properties, it is not recommended to use underscores to separate words in a variable. @serilizeName helps translate between the two.

@SerializedName("quota_remaining")

@Expose

private Integer quotaRemaining;

In this example, we are telling Gson that our JSON key quota_remaining should be mapped to the Java field quotaRemaining.  If both of these values were the same, i.e. if our JSON key was quotaRemaining. Just like the Java field, then there would be no need for the @serilizeName annotation on the field because Gson would map them automatically.

5- Create Retrofit instance

To request API with Retrofit, we need to create an instance using the Retrofit.Builder class.

package com.alburraq.retrofitexample.api;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient{

private static Retrofit retrofit = null;

public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}

6-Creating the API interfaces. 

This interface contains methods we are going to use to execute HTTP requests such as GET, POST, PUT, DELETE.

import com.alburraq.retrofitexample.model.Post;

 import retrofit2.Call;
 import retrofit2.http.DELETE;
 import retrofit2.http.Field;
 import retrofit2.http.FormUrlEncoded;
 import retrofit2.http.GET;
 import retrofit2.http.POST;
 import retrofit2.http.PUT;
 import retrofit2.http.Path;
 import retrofit2.http.Query;

 public interface APIServicePost {

     @POST("/posts")
     @FormUrlEncoded
     Call<Post> savePost(@Field("title") String title,
                         @Field("body") String body,
                         @Field("userId") long userId);

     @PUT("/posts/{id}")
     @FormUrlEncoded
     Call<Post> updatePost(@Path("id") long id,
                           @Field("title") String title,
                           @Field("body") String body,
                           @Field("userId") long userId);

     @DELETE("/posts/{id}")
     Call<Post> deletePost(@Path("id") long id);

     //This method is used for "POST"
     @FormUrlEncoded
     @POST("/api.php")
     Call<Post> post(
             @Field("method") String method,
             @Field("username") String username,
             @Field("password") String password
     );

     //This method is used for "GET"
     @GET("/api.php")
     Call<Post> get(
             @Query("method") String method,
             @Query("username") String username,
             @Query("password") String password
     );
 }

Parameters of the interface methods can have the following annotations:

@Path variable substitution for the API endpoint
@Query specifies the query key name with the value of the annotated parameter
@Body payload for the POST call
@Header specifies the header with the value of the annotated parameter

 

7-Creating Api Utils

Now are going to create a utility class.This class will have the base URL as a static variable and also provide the APIService interface to our application through static method.

package com.alburraq.retrofitexample.util;

 import com.alburraq.retrofitexample.api.RetrofitClient;
 import com.alburraq.retrofitexample.interfaces.APIServicePost;
 import com.alburraq.retrofitexample.interfaces.SOServiceGet;

 /**
  * Created by Al-Burraq-Dev on 9/12/2017.
  */

 public class ApiUtils{

     public static final String BASE_URL = "https://api.stackexchange.com/2.2/";

     public static SOServiceGet getSOService() {
         return RetrofitClient.getClient(BASE_URL).create(SOServiceGet.class);
     }
 }

8-Making Requests 

Inside the onCreate() method of the Activity, we initialize an instance of the ApiService interface and Request.

GET Request:

import retrofit2.Call;
 import retrofit2.Callback;
 import retrofit2.Response;

 public class MainActivity extends AppCompatActivity {

     private APIServicePost mService;
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate( savedInstanceState );
         setContentView(R.layout.activity_main );        .        .       
         mService = ApiUtils. getAPIService();        .        .
         loadAnswers();
     }

     public void loadAnswers() {
         mService.getAnswers().enqueue(new Callback<SOAnswersResponse>() {
             @Override
             public void onResponse(Call<SOAnswersResponse> call,     Response<SOAnswersResponse> response) {

                 if(response.isSuccessful()) {
                     mAdapter.updateAnswers(response.body().getItems());
                     Log.d("MainActivity", "posts loaded from API");
                 }else {
                     int statusCode  = response.code();
                     // handle request errors depending on status code
                 }
             }

             @Override
             public void onFailure(Call<SOAnswersResponse> call, Throwable t) {
 //                showErrorMessage();
                 Log.d("MainActivity", "error loading from API");

             }
         });
     }
 }
POST Request:
 package com.alburraq.retrofitexample.activities;

 import android.content.Intent;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.support.v7.widget.LinearLayoutManager;
 import android.support.v7.widget.RecyclerView;
 import android.util.Log;
 import android.widget.Toast;

 import com.alburraq.retrofitexample.R;
 import com.alburraq.retrofitexample.adapters.AnswersAdapter;
 import com.alburraq.retrofitexample.interfaces.SOServiceGet;
 import com.alburraq.retrofitexample.model.Item;
 import com.alburraq.retrofitexample.model.SOAnswersResponse;
 import com.alburraq.retrofitexample.util.ApiUtils;

 import java.util.ArrayList;

 import retrofit2.Call;
 import retrofit2.Callback;
 import retrofit2.Response;

 public class PostRequestActivity extends AppCompatActivity {

     private APIServicePost mService;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate( savedInstanceState );
         setContentView(R.layout.activity_main );         .        .        .       
         mService = ApiUtils. getAPIService();         .        .        . 
 sendPost(title, body);
     }  public void sendPost(String title, String body) {
     mAPIService.savePost(title, body, 1).enqueue(new Callback<Post>() {
         @Override
         public void onResponse(Call<Post> call, Response<Post> response) {

             if(response.isSuccessful()) {
                 showResponse(response.body().toString());
                 Log.i("PostActivity", "post submitted to API." + response.body().toString());
             }
         }

         @Override
         public void onFailure(Call<Post> call, Throwable t) {
             Log.e("PostActivity", "Unable to submit post to API.");
         }
     });
 }

9-Cancel Requests

private Call<Post> mCall;
 public sendPost(String title, String body) {
     mCall = mAPIService.savePost(title, body, 1);
     mCall.enqueue(new Callback<Post>() {
         @Override
         public void onResponse(Call<Post> call, Response<Post> response) {

             if(response.isSuccessful()) {
                 showResponse(response.body().toString());
                 Log.i(TAG, "post submitted to API." + response.body().toString());
             }
         }

         @Override
         public void onFailure(Call<Post> call, Throwable t) {

             if(call.isCanceled()) {
                 Log.e(TAG, "request was aborted");
             }else {
                 Log.e(TAG, "Unable to submit post to API.");
             }

         }
     });
 }

 public void cancelRequest() {
     mCall.cancel();
 }
Did you find apk for android? You can find new Free Android Games and apps.