albert sh
albert sh

Reputation: 1193

Detecting HTTPRequest failure

I have used the following code in order to send large number of HTTPRequests and as many of the calls are not successful, I want to detect them and save them in a new list ( UnsuccessfulURLsPhase1 ) and send them again.

Unfortunately when the HTTPRequest fails to be sent, the exception doesn't happen and I can not add the url to the new list.

Any hints is appreciated.

private static async Task CallURLAsync(string url)
{
    try
    {
        var content = new MemoryStream();
        var webReq = (HttpWebRequest)WebRequest.Create(url);

        using (WebResponse response = await webReq.GetResponseAsync())
        {
        }
    }
    catch ( Exception e )
    {
        UnsuccessfulURLsPhase1.Add(url);
        Console.WriteLine("\nException raised!");
        Console.WriteLine("\nMessage:{0}", e.Message);
    }
}

Upvotes: 0

Views: 58

Answers (1)

sumeet kumar
sumeet kumar

Reputation: 2648

Here is the code

        var content = new MemoryStream();
            var webReq = (HttpWebRequest)WebRequest.Create("http://google.com");

            using (WebResponse response = await webReq.GetResponseAsync())
            {
                HttpWebResponse res = (HttpWebResponse)response;
                if(res.StatusCode==HttpStatusCode.OK)
                {
                    //your code
                }

            }

Upvotes: 1

Related Questions