Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OkHttp API rate limit

Has OkHttp an integrated way of complying with an api rate request limit, or it has to be implemented externally? either case a hint on where to start is appreciated.

like image 873
Roberto Fernandez Avatar asked Feb 12 '16 14:02

Roberto Fernandez


1 Answers

An interceptor combined with a RateLimiter from Guava was a good solution to avoid receiving a 429 HTTP code.

Let's suppose we want a limit of 3 calls per second:

import java.io.IOException;

import com.google.common.util.concurrent.RateLimiter;

import okhttp3.Interceptor;
import okhttp3.Response;

public class RateLimitInterceptor implements Interceptor {
    private RateLimiter rateLimiter = RateLimiter.create(3);

    @Override
    public Response intercept(Chain chain) throws IOException {
        rateLimiter.acquire(1);
        return chain.proceed(chain.request());
    }
}
like image 71
Italo Borssatto Avatar answered Dec 25 '22 08:12

Italo Borssatto