Updated 1 February 2021
In the mobile app development lifecycle, communicating with the server(via API) to get or store data is one of the basic needs.
Retrofit is a type-safe REST client for Android, Java and Kotlin developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests. I am writing this blog is written to express a special case while using Retrofit.
Let’s understand the use case with an example.
Suppose we need to override our API requests to add a key in every API of our project then we need to edit all our API requests or we can edit our client to add a key in all requests. We can do it by overriding our requests.
Below is the code example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
Request request = chain.request(); Request.Builder builder = request.newBuilder(); if (request.method().equals("GET") || request.method().equals("PUT")) { HttpUrl originalHttpUrl = request.url(); HttpUrl url = originalHttpUrl.newBuilder() .addQueryParameter("lending_id", "disable") // Request customization: add request headers .build(); builder.url(url); } else { if ("POST".equals(request.method())) { if (request.body() instanceof FormBody) { FormBody.Builder bodyBuilder = new FormBody.Builder(); FormBody formBody = (FormBody) request.body(); // Copy the original parameters first for (int i = 0; i < formBody.size(); i++) { bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i)); } // Add common parameters formBody = bodyBuilder .addEncoded("lending_id", "disable") .build(); builder.post(formBody).build(); } } } builder.addHeader("Content-Type", "text/html") .addHeader("authKey", ApplicationSingleton.getInstance().getAuthKey()); |
In conclusion, in this way we can override our requests with Retrofit.
Thanks for viewing. Please get in touch via comment box for any discussions.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.