How to retry HTTP requests with OkHttp/Retrofit?

后端 未结 13 736
一向
一向 2020-12-07 09:04

I am using Retrofit/OkHttp (1.6) in my Android project.

I don\'t find any request retry mechanism built-in to either of them. On searching more, I read OkHttp seems

13条回答
  •  再見小時候
    2020-12-07 09:47

    As stated in the docs, a better might be to use the baked in authenticators, eg: private final OkHttpClient client = new OkHttpClient();

      public void run() throws Exception {
        client.setAuthenticator(new Authenticator() {
          @Override public Request authenticate(Proxy proxy, Response response) {
            System.out.println("Authenticating for response: " + response);
            System.out.println("Challenges: " + response.challenges());
            String credential = Credentials.basic("jesse", "password1");
            return response.request().newBuilder()
                .header("Authorization", credential)
                .build();
          }
    
          @Override public Request authenticateProxy(Proxy proxy, Response response) {
            return null; // Null indicates no attempt to authenticate.
          }
        });
    
        Request request = new Request.Builder()
            .url("http://publicobject.com/secrets/hellosecret.txt")
            .build();
    
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    
        System.out.println(response.body().string());
      }
    

提交回复
热议问题