public static string UploadStringOAuth2(this WebClient client, IStorage storage, string scopes, string path, string queryBody) { var creds = storage.GetCredentials(); client.AddBearer(creds); try { return(client.UploadString(path, queryBody)); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { if (((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized) { throw; } var secrets = storage.GetSecrets(); var authclient = new AuthClient(secrets, scopes, null, null); var newcreds = authclient.refreshAuthCode(creds); var storedcreds = storage.StoreCredentials(newcreds); client.AddBearer(storedcreds); return(client.UploadString(path, queryBody)); } throw; } }