Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Retrofit Library in Android

DZone's Guide to

Retrofit Library in Android

Let's take a look at Retrofit, which is a REST API client for Java.

· Integration Zone ·
Free Resource

The new Gartner Critical Capabilities report explains how APIs and microservices enable digital leaders to deliver better B2B, open banking and mobile projects.

Retrofit is a REST API Client for Java.
It is developed by Square Inc. and uses OkHttp library for HTTP Request. It is a simple library that is used for network transaction.
It is a very easy and fast library to retrieve and upload the data via Rest based web service.

Adding Dependency in Build.gradle

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.google.code.gson:gson:2.6.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
}

Adding Internet Permission in Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.kripashankar.countryappusingretrofit">
    <uses-permission android:name="android.permission.INTERNET" />

Retrofit mainly need three things which are following-

1. Retrofit Instance

You can create a Retrofit instance by Retrofit.Builder().
You have to specify the base URL and converter factory at the time of Retrofit instance creation as in the below example.

2. Interface

public interface ApiCallInterface
{
   @POST("api_name") // use @POST if api is post.
   Call<CountryResponse> getResponseData();
}

3. Model Class

Retrofit needs a model class (POJO) for sending and receiving requests.
Retrofit uses the model class for parsing the server response by using converters like Gson, Jackson.

Example

In the below example, we are going to display the country name and country code in RecyclerView.
For which as in createRetroFitBuilder() method of the example, first, we set the header using OkHttpClient class because the API is an authenticated API (set header only if API is authenticated). Then, we create a Retrofit instance and set the base URL and converter factory and call interface method, which interacts with the API on the background thread, and the success of the API can get in the onResponse() method of enqueue call back. Failure of the API can get in the onFailure() method of enqueue call back. After that, pass the list of country at adapter as in method setUpAdapterView() of the example:

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerViewCountry;
    private CountryListAdapter countryListAdapter;
    String BASE_URL = "http://example/retrofit/api/";
    CountryResponse countryResponse;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initializeView();
        createRetroFitBuilder();
    }

    private void initializeView()
    {
        recyclerViewCountry = (RecyclerView) findViewById(R.id.recyclerViewCountry);
    }

    private void createRetroFitBuilder() {
        // set header through OkHttpClient if API is authenticate API.
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        httpClient.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder()
                        .addHeader("timestamp", "153138130")
                        .addHeader("authentication_key", "QJTpP/7rai7D7KF2RcNK=")
                        .build();
                return chain.proceed(request);
            }
        });

        // creating retrofit object and set base url , Converter factory
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build();

        // calling of interface method which interact with API and give response in onResponse().
        ApiCallInterface apiCallInterface = retrofit.create(ApiCallInterface.class);
        Call<CountryResponse> call = apiCallInterface.getResponseData();

        call.enqueue(new Callback<CountryResponse>() {
            @Override
            public void onResponse(Call<CountryResponse> call, Response<CountryResponse> response)
            {
                countryResponse = response.body();
                setUpAdapterView();
            }

            @Override
            public void onFailure(Call<CountryResponse> call, Throwable t) {
                Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setUpAdapterView() {
        if(countryResponse != null)
        {
            countryListAdapter = new CountryListAdapter(countryResponse,this);
            LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
            mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerViewCountry.setLayoutManager(mLayoutManager);
            recyclerViewCountry.setAdapter(countryListAdapter);
        }

    }

}

The new Gartner Critical Capabilities for Full Lifecycle API Management report shows how CA Technologies helps digital leaders with their B2B, open banking, and mobile initiatives. Get your copy from CA Technologies.

Topics:
retrofit library ,network communication ,api requests ,tutorial ,integration

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}