This is the way I do server request to some endpoints from Azure:
public T SingleRead<T>(string url, string method, object entity = null)
{
T returnValue = default(T);
var resp = GetRESTResponse(url, method, entity);
string responseText = GetResponseText(resp);
try
{
returnValue = JsonConvert.DeserializeObject<T>(responseText);
}
catch (Exception ex)
{
return default(T);
}
return returnValue;
}
private HttpWebResponse GetRESTResponse(string url, string method, object entity = null)
{
var address;
if (!url.StartsWith("http"))
{
if (!url.StartsWith("/")) url = $"/{url}";
address = baseAddress + url;
}
else
{
address = url;
}
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(address);
req.Method = method;
if (entity != null)
{
byte[] byteArray = Encoding.Default.GetBytes(JsonConvert.SerializeObject(entity));
req.ContentLength = byteArray.Length;
req.ContentType = "application/json";
Stream dataStream = req.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Flush();
dataStream.Close();
}
HttpWebResponse resp;
try
{
resp = (HttpWebResponse)req.GetResponse();
}
catch (WebException e)
{
Log(e.Reponse);
resp = (HttpWebResponse)e.Response;
}
return resp;
}
private static string GetResponseText(HttpWebResponse resp)
{
var encoding = Encoding.ASCII;
string responseText = ".";
using (var reader = new StreamReader(resp.GetResponseStream(), encoding))
{
responseText = reader.ReadToEnd();
}
if (resp.StatusCode == HttpStatusCode.InternalServerError || resp.StatusCode == HttpStatusCode.BadRequest || resp.StatusCode == HttpStatusCode.NotFound)
{
return "";
}
return responseText;
}
It works quite often. Sometimes, it doesn't, and I get the a "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond" error from the Log.
Is there some wrong in the procedure, or it could be a "timeout" by endpoint? The called server users says "we don't have any problem, and we don't get the request".
Not sure if its the fault of the code above (maybe some stream not closed?). But I don't see any problem. Do you see any trouble in this?