Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Response status code

I have this simple function to get HTML pages and return it as a string; though sometimes I get a 404. How can I only return the HTML string only if the request was successful, and return something like BadRequest when it's a 404 or any other error status code?

public static string GetPageHTML(string link)
{
    using (WebClient client= new WebClient())
    {
        return client.DownloadString(link);
    }
}
like image 203
user1590636 Avatar asked Mar 08 '13 08:03

user1590636


People also ask

What is a response status code?

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: Informational responses ( 100 – 199 ) Successful responses ( 200 – 299 ) Redirection messages ( 300 – 399 )

What is a 402 response code?

The HTTP 402 Payment Required is a nonstandard response status code that is reserved for future use. This status code was created to enable digital cash or (micro) payment systems and would indicate that the requested content is not available until the client makes a payment.

What is a 422 error?

The HyperText Transfer Protocol (HTTP) 422 Unprocessable Entity response status code indicates that the server understands the content type of the request entity, and the syntax of the request entity is correct, but it was unable to process the contained instructions.

What is a 201 response code?

The HTTP 201 Created success status response code indicates that the request has succeeded and has led to the creation of a resource.


1 Answers

You could catch the WebException:

public static string GetPageHTML(string link)
{
    try
    {
        using (WebClient client = new WebClient())
        {
            return client.DownloadString(link);
        }
    }
    catch (WebException ex)
    {
        var statusCode = ((HttpWebResponse)ex.Response).StatusCode;
        return "An error occurred, status code: " + statusCode;
    }
}

Of course it would be more appropriate to catch this exception in the calling code and not even attempt to parse the html instead of putting the try/catch in the function itself.

like image 136
Darin Dimitrov Avatar answered Sep 28 '22 01:09

Darin Dimitrov