Wednesday, November 1, 2017

Retrofit

Retrofit:
Today we are going to look at  awesome library Retrofit to make the http calls. Retrofit is denitely the better alternative to volley in terms of ease of use, performance, extensibility and other things. It is a type-­safe REST client for Android built by Square. Using this tool android developer can make all network stuff much more easier.



Step 1


Open build.gradle and add Retrofit, Gson dependencies.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'

    // retrofit, gson
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
}

Step 2

Add INTERNET permissions in AndroidManifest.xml file

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

Step 3

//Retrofit
private parsing p;
private Retrofit retrofit;
private int mStatusCode;
private APICallInterface service;
final OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.build();



Step 4

In onCreate():

p = new parsing();
/** Creating REST API Calls **/
retrofit = new Retrofit.Builder()
.baseUrl(p.url_server)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
service = retrofit.create(APICallInterface.class);




private void callRetrofit() {

        String strUrl = baseUrl + "posts";

        Call<ResponseBody> caller = service.callAPI(strUrl);
        caller.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> caller, retrofit2.Response<ResponseBody> response) {

                try {
                    String reponse = response.body().string();
                    mStatusCode = response.code();
                    Log.e("Response",reponse);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

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

                if (t instanceof SocketTimeoutException) {
                    Log.v("SocketTimeOut", "SocketTimeOut");
                    Toast.makeText(MainActivity.this, "TimeOut"
                            , Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


Step 5

create Interface in app folder

public interface APICallInterface {

   @GET
   @Headers("Connection:close")
   Call<ResponseBody> callAPI(@Url String url);

   @GET
   @Headers("Connection:close")
   Call<ResponseBody> callAPI(@Url String url, @QueryMap Map<String, String> parameters);

   @POST
   @Headers("Connection:close")
   Call<ResponseBody> postToAPI(@Url String url, @Body RequestBody parameter);

   @PUT
   @Headers("Connection:close")
   Call<ResponseBody> putToAPI(@Url String url, @Body RequestBody parameter);


}


Download

Sample Project 

Happy Coding....☺☺☺

1 comment: