I am developing a .NET plugin that translates some data from Microsoft Dynamics Nav 2013 into Json and sends it to a webservice on a clients server.
The webservice successfully transfers the first two times i call the send method but at the third call i recieve a timeout.
Ive searched the internet and discovered that this is due to not properly closing the webresponse but i cant seem to make it work.
The following code is a lightly modified version of my send method to display my issue.
Perhaps one of you can identify the problem that causes the third consecutive call to time out?
public string SendData(string schoolName)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://" + schoolName + ".*****.dk/api/v2/stays.json");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(container);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
HttpWebResponse httpResponse = null;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string statusCode;
return statusCode = httpResponse.StatusCode + " " + "Eleven blev sendt til ******";
}
catch (Exception e)
{
throw e;
}
finally
{
if (httpResponse != null)
{
httpResponse.Close();
}
}
}
}
Ive attemped to simplify the code as comments suggested but the issue still persists. The code now looks like this:
public string SendData(string schoolName)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://" + schoolName + ".****.dk/api/v2/stays.json");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(container);
streamWriter.Write(json);
}
using(HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
string statusCode;
return statusCode = httpResponse.StatusCode + " " + "Eleven blev sendt til ****";
}
}