2

I want to change the read timeout on OkHttp client using retrofit for one api call. To be clear, I have one end point that can take very long, I need to increase it's timeout and only the timeout for that one api call. Is there a way I can do this through annotations? Is there a way I can do this without changing the timeouts for the rest of the app?

Ali
  • 12,354
  • 9
  • 54
  • 83

2 Answers2

2

I'm facing a similar situation. I solve my problem providing two Api instances in my ApiModule, each one with your own OkHttpClient. Use @Named to identify each one.

I tried to avoid providing two instances only for a timeout configuration, seems a little strange for me, but since my API instance is a singleton (for performance), I could not see other solution.

Ismael Di Vita
  • 1,806
  • 1
  • 20
  • 35
0

You can actually do a per call configuration

Copy the default builder and make another client

private final OkHttpClient client = new OkHttpClient();

  public void run() throws Exception {
    Request request = new Request.Builder()
        .url("http://blah_blah_api.com/") // This URL is served with a 1 second delay.
        .build();

    try {
      // Copy to customize OkHttp for this request.
      OkHttpClient copy = client.newBuilder()
          .readTimeout(500, TimeUnit.MILLISECONDS)
          .build();

      Response response = copy.newCall(request).execute();
      System.out.println("Response 1 succeeded: " + response);
    } catch (IOException e) {
      System.out.println("Response 1 failed: " + e);
    }

    try {
      // Copy to customize OkHttp for this request.
      OkHttpClient copy = client.newBuilder()
          .readTimeout(3000, TimeUnit.MILLISECONDS)
          .build();

      Response response = copy.newCall(request).execute();
      System.out.println("Response 2 succeeded: " + response);
    } catch (IOException e) {
      System.out.println("Response 2 failed: " + e);
    }
  }
rakesh kashyap
  • 1,418
  • 22
  • 41
  • I'm using Retrofit with Dagger-2, any way of solving this without creating named variables for OkHttp? – Ali Aug 18 '16 at 02:01
  • I have not worked on dagger. I am aware that this is a dependency injection tool. How about creating a helper class and passing the class variable to your activity as a dependency.. Sorry if I am misleading. – rakesh kashyap Aug 18 '16 at 02:54