I'm actually facing an issue with a httpWebResponse that stop my thread.
I call an ApiCall method in a looping thread every 2 seconds. This works most of the time. But sometimes the request.GetResponse()
throws a WebException and stops my main thread loop. It freezes the application without crashing it. It can be retried 5 times(MaxRetries) without working properly. I don't understand what's going on.
Here's the code part on an ApiCall Method. I don't really know who it works. So picked up some code here and there. I must miss something..., but what?
public T CallWithJsonResponse<T>(string uri, bool hasEffects, params Tuple<string, string>[] headers)
{
if (simulate && hasEffects)
{
Debug.WriteLine("(simulated)" + GetCallDetails(uri));
return default(T);
}
Debug.WriteLine(GetCallDetails(uri));
var request = HttpWebRequest.CreateHttp(uri);
foreach (var header in headers)
{
request.Headers.Add(header.Item1, header.Item2);
}
HttpWebResponse response = null;
request.Timeout = 300000;
for (int i = 0; i < MaxRetries; i++)
{
try
{
response = null;
using (response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
try
{
using (var sr = new StreamReader(response.GetResponseStream()))
{
var content = sr.ReadToEnd();
var jsonResponse = JsonConvert.DeserializeObject<ApiCallResponse<T>>(content);
sr.Close();
response.Close();
if (jsonResponse.success)
{
//GC.Collect();
GC.WaitForPendingFinalizers();
return jsonResponse.result;
}
else
{
Console.WriteLine(new Exception(jsonResponse.message.ToString()));
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error - Call Details=" + GetCallDetails(uri) + "Exeption: " + ex.ToString());
}
}
else
{
Console.WriteLine("Error - StatusCode=" + response.StatusCode + " Call Details=" + GetCallDetails(uri));
}
}
}
catch (WebException wex)
{
if (wex.Response != null)
{
Console.WriteLine("ERROR (web exception, response generated): " + Environment.NewLine + new StreamReader(wex.Response.GetResponseStream()).ReadToEnd());
}
else
{
Console.WriteLine("ERROR (web exception, NO RESPONSE): " + wex.Message + wex.StackTrace);
}
Console.WriteLine("Error - Call Details=" + GetCallDetails(uri));
}
catch (Exception ex)
{
Console.WriteLine("Error - Call Details=" + GetCallDetails(uri) + "Exception: " + ex.ToString());
}
}
return default(T);
}
private static string GetCallDetails(string uri)
{
StringBuilder sb = new StringBuilder();
var u = new Uri(uri);
sb.Append(u.AbsolutePath);
if (u.Query.StartsWith("?"))
{
var queryParameters = u.Query.Substring(1).Split('&');
foreach (var p in queryParameters)
{
if (!(p.ToLower().StartsWith("api") || p.ToLower().StartsWith("nonce")))
{
var kv = p.Split('=');
if (kv.Length == 2)
{
if (sb.Length != 0)
{
sb.Append(", ");
}
sb.Append(kv[0]).Append(" = ").Append(kv[1]);
}
}
}
}
return sb.ToString();
}