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);
}
}
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 )
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.
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.
The HTTP 201 Created success status response code indicates that the request has succeeded and has led to the creation of a resource.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With