I have built a WebRequest in a WPF application into a background worker, but it is hanging if the website does not return a 404 error. There is a timeout, and found that some people have also had the same problem with the timeout not working and making the WebRequest hang. I tried to implement the code recommended for fixing the hang which is where I have the using()
lines, but it still doesn't work.
// Try to login, if error, report
String method = "POST";
String postdata = "postdata=test";
String url = "http://localhost:90/randomurlthatdoesntwork";
WebRequest rqst = HttpWebRequest.Create(url);
rqst.Method = method;
if (!String.IsNullOrEmpty(postdata))
{
rqst.ContentType = "application/x-www-form-urlencoded";
byte[] byteData = UTF8Encoding.UTF8.GetBytes(postdata);
rqst.ContentLength = byteData.Length;
rqst.Timeout = 10000;
using (Stream postStream = rqst.GetRequestStream())
{
// I believe this is where the request hangs
postStream.Write(byteData, 0, byteData.Length);
postStream.Close();
rqst.GetResponse().Close();
rqst.GetRequestStream().Close();
}
}
((HttpWebRequest)rqst).KeepAlive = true;
loginProcess.ReportProgress(90);
using (var response1 = rqst.GetResponse())
{
using (var responseStream1 = response1.GetResponseStream())
{
using (var reader1 = new StreamReader(responseStream1))
{
string strRsps = reader1.ReadToEnd();
loginProcess.ReportProgress(95);
loginVars = strRsps;
reader1.Close();
}
args.Result = "SUCCESS";
}
}