How to dynamically set headers in Retrofit (Android)

前端 未结 4 686
无人及你
无人及你 2020-11-29 01:07

I am using an API that uses an authorization scheme that requires a special \"X-Authorization\" header to be set to authenticate the request. For example, this Retrofit setu

4条回答
  •  半阙折子戏
    2020-11-29 02:03

    Dynamic Header In Retrofit 2

    I have struggled too much to add Dynamic Header In Retrofit 2.

    I have gone through so many blogs and StackOver flow. Everyone has shown example with Interceptor.

    And it’s not a wise thing ,just for one API call we need to do that much work.

    You just have to add @HeaderMap as argument of fun. I have done in very simple way :-

    In Kotlin

        val headers = HashMap()
        headers["KEY_AUTHORIZATION"] = "paste AUTHORIZATION value here"
        headers["KEY_TOKEN"] = "paste TOKEN value here"
    
        val jsonObject= JsonObject()
    
    I am passing here header and other data also
    Calling of fun:-
    
    postEvent(headers,jsonObject)
    
    API Declaration 
    
        @POST("/v1/post_data")
        fun postEvent(@HeaderMap headers: Map, @Body jsonObject: JsonObject): Call
    
    API Declaration with RxAndroid
    
        @POST("/v1/post_data")
        fun postEvent(@HeaderMap headers: Map, @Body jsonObject: JsonObject): Single
    

    2nd argument here i have JsonObject. You can replace with anything whatever you need to pass or you can remove it also.

    In Java

     HashMap headers = new HashMap();
        headers.put("KEY_AUTHORIZATION","paste AUTHORIZATION value here");
        headers.put("KEY_TOKEN", "paste TOKEN value here");
    
        JsonObject jsonObject= new JsonObject();
    
    I am passing here header and other data also
    
    Calling of fun:-
    postEvent(headers,jsonObject);
    
        API Declaration 
        @POST("/v1/post_data")
        Call postEvent(@HeaderMap Map headers, @Body JsonObject jsonObject);
    
    API Declaration with RxAndroid
    
        @POST("/v1/post_data")
        Single postEvent(@HeaderMap Map headers, @Body JsonObject jsonObject);
    

    2nd argument here i have JsonObject. You can replace with anything whatever you need to pass or you can remove it also.

提交回复
热议问题