init
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public class Query
|
||||
{
|
||||
public static async Task<string> Get(string urlPath, bool withAuth, Dictionary<string,string> extraParameters = null)
|
||||
{
|
||||
return await Call("GET", urlPath, withAuth, extraParameters);
|
||||
}
|
||||
|
||||
public static async Task<string> Post(string urlPath, bool withAuth, string postData, Dictionary<string,string> extraParameters = null)
|
||||
{
|
||||
return await Call("POST", urlPath, withAuth, extraParameters, postData);
|
||||
}
|
||||
|
||||
public static async Task<string> Call(string method, string urlPath, bool withAuth,
|
||||
Dictionary<string,string> extraParameters = null, string postData = null)
|
||||
{
|
||||
string finalPath = LocalConfig.homeserver + urlPath;
|
||||
|
||||
for (int i=0; i<10; i++)
|
||||
{
|
||||
using (var client = new HttpClient())
|
||||
{
|
||||
if (withAuth)
|
||||
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + LocalConfig.authToken);
|
||||
|
||||
if (extraParameters != null)
|
||||
{
|
||||
foreach ((string key, string value) in extraParameters)
|
||||
{
|
||||
client.DefaultRequestHeaders.Add(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
HttpResponseMessage response;
|
||||
if (method == "POST")
|
||||
{
|
||||
response = await client.PostAsync(finalPath, new StringContent(postData));
|
||||
} else {
|
||||
response = await client.GetAsync(finalPath);
|
||||
}
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
return await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Retry logic
|
||||
// ex: https://spec.matrix.org/v1.14/client-server-api/#rate-limiting
|
||||
if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
|
||||
{
|
||||
if (i != 9)
|
||||
await Task.Delay(i*1000 + 100);
|
||||
else
|
||||
Console.WriteLine("FATAL - too many requests even though we delayed");
|
||||
} else
|
||||
{
|
||||
Console.WriteLine("Problem with API request:" + response.StatusCode);
|
||||
|
||||
if ((int) response.StatusCode >= 400 && (int) response.StatusCode < 500)
|
||||
{
|
||||
Console.WriteLine("Giving up on this one due to status code.");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (i != 9)
|
||||
Console.WriteLine("Retry...");
|
||||
else
|
||||
Console.WriteLine("FATAL");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user