string CreateFile(Stream content, string fileName, string mimeType, string folderId, string accessToken){ var bytes = Encoding.UTF8.GetBytes( "\r\n--boundary\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{\"title\":\"" + fileName + "\",\"parents\":[{\"id\":\"" + folderId + "\"}]}" + "\r\n--boundary\r\nContent-Type: " + mimeType + "\r\n\r\n"); var tmpStream = new MemoryStream(); tmpStream.Write(bytes, 0, bytes.Length); content.CopyTo(tmpStream); bytes = Encoding.UTF8.GetBytes("\r\n--boundary--\r\n"); tmpStream.Write(bytes, 0, bytes.Length); var request = WebRequest.Create("https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart"); request.Method = "POST"; request.Headers.Add("Authorization", "Bearer " + accessToken); request.ContentType = "multipart/related; boundary=boundary"; request.ContentLength = tmpStream.Length; var buffer = new byte[2048]; int readed; tmpStream.Seek(0, SeekOrigin.Begin); while ((readed = tmpStream.Read(buffer, 0, 2048)) > 0) { request.GetRequestStream().Write(buffer, 0, readed); } return request.GetResponse().GetResponseStream(); }
final RateLimiter driveApiRateLimiter = RateLimiter.create(QUOTA_RATE_PER_SECOND);
public Result performDriveApiCall(driveApiRateLimiter, otherParams){ driveApiRateLimiter.acquire(); // blocks according to rate // make API call...
1, 2, 4, 8, 16, 32, 60, 60, 60
ExponentialBackOff backoff = new ExponentialBackOff.Builder() .setInitialIntervalMillis(ONE_SECOND) .setMultiplier(2.0) .setMaxIntervalMillis(ONE_MINUTE) .setMaxElapsedTimeMillis(FIVE_MINUTES) .build();
1.04, 1.9, 4.23, 7.8, etc.
.98, 2.04, 4.1, 8.15, etc.
builder.setRandomizationFactor(RANDOMIZATION_FACTOR);
private HttpBackOffUnsuccessfulResponseHandler handler = new HttpBackOffUnsuccessfulResponseHandler(backoff); public void initialize(HttpRequest request){ request.setUnsuccessfulResponseHandler(handler); }