Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package com.github.jreddit.utils.restclient;
 
Reddit's API access rules require that no more than 1 request is made every 2 seconds (i.e 30 requests per minute). This client makes it easy to track the time, and ensures that the 2 seconds pass between each request. Its a singleton class, use PoliteRestClient.get() to get an instance. This is so all classes / requests are limited by the same limitation
public class PoliteHttpRestClient extends HttpRestClient
{

Waiting time in milliseconds.
    private static final long WAIT_TIME = 2000;
    
    
Last time a request was made.
    private long lastReqTime = 0;
    
    public PoliteHttpRestClient() {
    	super();
    }
    
    public PoliteHttpRestClient(HttpClient httpClientResponseHandler<ResponseresponseHandler) {
    	super(httpClientresponseHandler);
    }
    public Response get(String urlPathString cookie)
    {
        waitIfNeeded();
        Response resp = super.get(urlPathcookie);
        noteTime();
        return resp;
    }
    public Response post(String apiParamsString urlPathString cookie)
    {
        waitIfNeeded();
        Response resp = super.post(apiParamsurlPathcookie);
        noteTime();
        return resp;
    }
    private void noteTime()
    {
         = System.currentTimeMillis();
    }
    private void waitIfNeeded()
    {
        if ( == 0)
            return;
        long elapsed = System.currentTimeMillis() - ;
        if (elapsed >= )
            return;
        long toWait =  - elapsed;
        try
        {
            Thread.sleep(toWait);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
    
New to GrepCode? Check out our FAQ X