private HttpWebResponse SendHttpWebRequest_(
string path, string method, MemoryStream body, string contentType, string accept, string contentEncoding)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
void send()
{
request = null;
response = null;
Stopwatch sw = Stopwatch.StartNew();
try
{
try
{
var requestUri = string.IsNullOrEmpty(path) ?
ServerUrl : new Uri(ServerUrl, path);
request = CreateHttpWebRequest_(
requestUri, method, body, contentType, accept, contentEncoding);
if (request == null)
{
throw new NullReferenceException("request is null");
}
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
if (request == null || ex.Response == null)
{
throw;
}
response = (HttpWebResponse)ex.Response;
}
}
catch (Exception ex2)
{
if (request != null && RequestFailed != null)
{
var args = new HttpRequestFailedEventArgs(sw.Elapsed, request, ex2);
CommonUtils.DontThrow(() => RequestFailed(this, args));
}
throw;
}
if (RequestCompleted != null)
{
var args = new HttpRequestCompletedEventArgs(
sw.Elapsed, request, response);
CommonUtils.DontThrow(() => RequestCompleted(this, args));
}
}
int wait = 500;
int retriesLeft = 2;
do
{
try
{
send();
retriesLeft = 0;
}
catch
{
CommonUtils.DontThrow(() => response?.Close());
Thread.Sleep(wait);
wait *= 2;
wait = Math.Min(10000, wait);
}
} while (retriesLeft-- > 0);
if (response == null)
{
throw new NullReferenceException("response is null");
}
//while (Retry != null && Retry(request, response))
//{
// CommonUtils.DontThrow(() => response.Close());
// Thread.Sleep(wait);
// wait *= 2;
// wait = Math.Min(10000, wait);
// send();
//}
if (response == null)
{
throw new NullReferenceException("response object is null.");
}
if (AcceptLongRunningTasks)
{
var statusUrl = response.Headers[HttpResponseHeader.Location];
if (statusUrl != null && response.StatusCode == HttpStatusCode.Accepted)
{
response.Close();
wait = 500;
while (true)
{
using (response = Get(statusUrl))
{
if (response.StatusCode == HttpStatusCode.Created)
{
return(Delete(
response.Headers[HttpResponseHeader.Location], accept));
}
if (response.StatusCode == HttpStatusCode.OK)
{
Thread.Sleep(wait);
wait *= 2;
wait = Math.Min(10000, wait);
continue;
}
// Something went wrong.
return(response);
}
}
}
}
return(response);
}