Reputation: 11
I need check an url exist or not, then my code :
private bool CheckConnection(String URL)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.UseDefaultCredentials = true;
request.KeepAlive = false;
request.Timeout = 5000;
request.ReadWriteTimeout = 5000;
request.ServicePoint.ConnectionLeaseTimeout = 5000;
request.ServicePoint.MaxIdleTime = 5000;
bool bReturn = false;
using (var response = (HttpWebResponse)request.GetResponse())
{
bReturn = (response.StatusCode == HttpStatusCode.OK);
}
request.Abort();
return bReturn;
}
catch
{
return false;
}
}
I receive message "timeout" on 3rd call, I search and fix but can not success. Can anyone help me?
Thanks all
Upvotes: 1
Views: 937
Reputation: 371
I was struggling with the same problem and after some R&D i troubleshooted by closing the HttpResponse
object after asserting the response code in loop: response.Close();
My Code:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
int respcode = (int)response.StatusCode;
Assert.IsTrue(respcode == 302 || respcode == 200);
response.Close();
Upvotes: 3
Reputation: 3681
Try below code.Once i had same issue and i fixed it using this example. Hope this work for you too.
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "key", "This is a test that posts this string to a Web server." }
};
string url = "http://www.contoso.com/PostAccepter.aspx";
byte[] result = client.UploadValues(url, values);
Console.WriteLine(Encoding.UTF8.GetString(result));
}
Upvotes: 0