In the past, we've explored how to add request headers with Retrofit and how to statically change request headers with OkHttp. In this blog post, we'll dig into how you can add a dynamic amount of request headers to your Retrofit requests.
This is a new feature of Retrofit 2.1, so make sure you've updated your app before you try it out.
Of course, this is not the only post in our Retrofit series. If you're interested in the other topics, check the following series outline:
Retrofit Series Overview
- Getting Started and Creating an Android Client
- Basics of API Description
- Creating a Sustainable Android Client
- URL Handling, Resolution and Parsing
- How to Change API Base Url at Runtime
- Multiple Server Environments (Develop, Staging, Production)
- Share OkHttp Client and Converters between Retrofit Instances
- Upgrade Guide from 1.9
- Beyond Android: Retrofit for Java Projects
- How to use OkHttp 3 with Retrofit 1
- Synchronous and Asynchronous Requests
- Send Objects in Request Body
- Add Custom Request Header
- Manage Request Headers in OkHttp Interceptor
- Dynamic Request Headers with @HeaderMap
- Multiple Query Parameters of Same Name
- Optional Query Parameters
- Send Data Form-Urlencoded
- Send Data Form-Urlencoded Using FieldMap
- How to Add Query Parameters to Every Request
- Add Multiple Query Parameter With QueryMap
- How to Use Dynamic Urls for Requests
- Constant, Default and Logic Values for POST and PUT Requests
- Cancel Requests
- Reuse and Analyze Requests
- Optional Path Parameters
- How to Send Plain Text Request Body
- Customize Network Timeouts
- How to Trust Unsafe SSL certificates (Self-signed, Expired)
- Dynamic Endpoint-Dependent Interceptor Actions
- How to Update Objects on the Server (PUT vs. PATCH)
- How to Delete Objects on the Server
- Introduction to (Multiple) Converters
- Adding & Customizing the Gson Converter
- Implementing Custom Converters
- How to Integrate XML Converter
- Access Mapped Objects and Raw Response Payload
- Supporting JSON and XML Responses Concurrently
- Handling of Empty Server Responses with Custom Converter
- Send JSON Requests and Receive XML Responses (or vice versa)
- Unwrapping Envelope Responses with Custom Converter
- Wrapping Requests in Envelope with Custom Converter
- Define a Custom Response Converter
Dynamic Request Headers
Unfortunately, the approaches we've shown you in the previous blog posts are all static. While you can change the value of the headers, you cannot dynamically select which headers you actually send. If you need to decide at runtime which headers are added to your request, @HeaderMap
is a possible solution.
Similar to the @Header
annotation, you need to declare the @HeaderMap
as one of the interface parameters. The type of the parameter needs to an implementation of the Java Map interface:
public interface TaskService {
@GET("/tasks")
Call<List<Task>> getTasks(
@HeaderMap Map<String, String> headers
);
}
Using the interface we've declared above is quite simple. You can just create a Map
instance and fill it with values depending on your needs. Retrofit will add every non-null element of the @HeaderMap
as a request header.
TaskService taskService = ServiceGenerator.createService(TaskService.class);
Map<String, String> map = new HashMap<>();
map.put("Page", String.valueOf(page));
if (BuildConfig.DEBUG) {
map.put("Accept", "application/vnd.yourapi.v1.full+json");
map.put("User-Agent", "Future Studio Debug");
}
else {
map.put("Accept", "application/json");
map.put("Accept-Charset", "utf-8");
map.put("User-Agent", "Future Studio Release");
}
Call<List<Task>> call = taskService.getTasks(map);
// Use it like any other Retrofit call
Outlook
In this blog post, you've learned how you can use the new @HeaderMap
annotation to add a dynamic amount of request headers during runtime. This is a fantastic extension of the previous options for request headers. We love it!
If you've feedback or a question, let us know in the comments or on twitter @futurestud_io.
Make it rock & enjoy coding!