I need make a GET call to a REST api which is rate limited. I can find out what the current rate limit is by making a call and checking the HTTP headers. If I've exceeded my rate limit, I should wait for a bit before retrying. I'd like to write something like:
val conn = connect(url, _.getHeaderField("X-RateLimit-Remaining").toInt > 0, 500)
I have a working solution using a var, a while loop and some repetitious code, but it feels clunky:
def connect(url: String, succeeded: URLConnection=>Boolean, waitMillis: Int) = {
var conn = new URL(url).openConnection
while (!succeeded(conn)) {
Thread.sleep(waitMillis)
conn = new URL(url).openConnection
}
conn
}
Is there a cleaner way to do this?