DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. 5 Ways to Customize Retrofit Library in Android

5 Ways to Customize Retrofit Library in Android

This how-to provides tips, with code, on customizing Android Retrofit Library, including enabling logging and overriding connection timeouts.

Madhav Bhattarai user avatar by
Madhav Bhattarai
·
Apr. 04, 17 · Tutorial
Like (5)
Save
Tweet
Share
6.59K Views

Join the DZone community and get the full member experience.

Join For Free

Retrofit is a type-safe HTTP client for Android built on top of OkHttp Stack. Most of the boilerplate code is hidden inside the library, making your code clean, maintainable, and easily extensible. In this article, I will discuss five ways to customize Retrofit Library. For a simple step-by-step guide on implementing the Retrofit library, see this Retrofit Android tutorial.

1. Adding a Custom Header in Retrofit

Sometimes you need to add a custom header where the goal is to override a certain property of a request or to pass some data about a client. The example below shows how to add an authorization to every request.

Setting Up

  • Add the following dependency in your build.gradle:  
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
  • Create a new class called CustomInterceptor.java, that implements the Interceptor interface provided by Okhttp3. To add a custom header, you should add your header property in the intercept() method. See the example below:
    public class CustomInterceptor implements Interceptor {
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();
            builder.addHeader("authorization", "c28b544426db927b5d1caa8b00ae50f8");
            return chain.proceed(builder.build());
        }
    }

2. Passing Different JSON Structures to a Single API

To perform a post request, you need to pass your request object to API. This prevents sending a different type of object to your API. For example, consider passing a filter query to your API. Filter parameters may include price, relevance, color, etc. For a normal case, you may need to create a four API that filters according to the different property. See below:

    @POST("/filter")
    Call<OtpVerificationResponse> filter(@Body Price price);

    @POST("/filter")
    Call<OtpVerificationResponse> filter(@Body Relevance relevance);

To overcome this limitation, you can create only one API as shown below:

  @POST("/filter")
    Call<OtpVerificationResponse> filter(@Body Object object);

The above API will accept any type of an object.

3. Overriding a Connection Timeout

To override a connection timeout, you just need to create an object of OkHttpClient and pass it in Retrofit builder method, as shown below:

Creating an OkHttpClient Object With a Custom Timeout

  • final OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .readTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .build();

  • Passing an OkHttpClient Object to Retrofit Builder Method

    retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .client(okHttpClient)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();


    4. Working With Different Response Types

    Web service may vary in terms of response format. Some web services return a response in JSON, while others are in XML. You don't need to change your code in order to work with different response formats. You can simply override the converter type in the Builder method of Retrofit. See the example below:

    For JSON Converter Using GSON

    • Add the following dependency in your build.gradle file:  compile 'com.squareup.retrofit2:converter-gson:2.1.0' 
    • Change the converter type while building a Retrofit object:
      Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(EndPoint.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();


    For XML converter, see Sourceforge documentation. 

    5. Enabling Logging

    To enable logging, add the following dependency in your build.gradle file:

     compile 'com.squareup.okhttp3:logging-interceptor:3.3.1' 

    Make the following changes to your code:

     OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
            httpClient.addInterceptor(logging);
    
        Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(EndPoint.BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();


    For more tutorials like this, see Learnzone.

    Happy coding!

    Library Android (robot)

    Opinions expressed by DZone contributors are their own.

    Popular on DZone

    • Understanding gRPC Concepts, Use Cases, and Best Practices
    • Spring Cloud: How To Deal With Microservice Configuration (Part 1)
    • What Should You Know About Graph Database’s Scalability?
    • Kotlin Is More Fun Than Java And This Is a Big Deal

    Comments

    Partner Resources

    X

    ABOUT US

    • About DZone
    • Send feedback
    • Careers
    • Sitemap

    ADVERTISE

    • Advertise with DZone

    CONTRIBUTE ON DZONE

    • Article Submission Guidelines
    • Become a Contributor
    • Visit the Writers' Zone

    LEGAL

    • Terms of Service
    • Privacy Policy

    CONTACT US

    • 600 Park Offices Drive
    • Suite 300
    • Durham, NC 27709
    • support@dzone.com
    • +1 (919) 678-0300

    Let's be friends: