Search code examples
androidretrofit2okhttpconnection-timeout

Retrofit2/OKHttp3: set custom per-request headers programatically


How can I specify custom per-request read/write/connect timeouts with Retrofit2/OKHttp3? Something like

Response<Listings> response = 
    ApiProvider.getServer1().getListings().setTimeouts(10000).execute();

Currently timeouts are set to 30s which is fine, but in one specific case I am bound by 10s execution limit and I need to make sure I get web response before that.

Based on this nice GitHub comment I know I could set custom timeouts with @Header and parsing them in OKHttp Interceptor, but as said before, I need custom timeouts for just one specific API call in a specific context.

I also found this answer (option 1) Using OkHttp 2.2+ use Interceptor), but I can't see how I can tell to interceptor that I need custom timeouts.


Solution

  • To set header dynamically, you can pass value of header as a parameter in your method using @Header annotation.

    Example:

    @GET("some/url")
    Call<SomeClass> doSomething(@Header("CONNECT_TIMEOUT") String timeOut);