Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 404 error page content with Http WebRequest?

I use Http WebRequest with Vb.Net to download content. Everything is working fine, but now I have a problem:

I want to download this website which is an example for a 404 Error page with content: http://www.boris-koch.de/404seiteyeah

But then I get this Error: "Webexception - 404". And I can't read the content of the page because the response is nothing. So do you know a way how to handle it and to get the content of the 404 error page? Thanks a lot. :)

like image 940
Johan Avatar asked Dec 29 '25 03:12

Johan


1 Answers

You can access the WebResponse within the WebException via the Response property. That will have the response data in. For example, in C# (the VB code would be very similar):

using System;
using System.IO;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        string url = "http://www.boris-koch.de/404seiteyeah";
        WebRequest req = WebRequest.Create(url);
        try
        {
            using (WebResponse response = req.GetResponse())
            {
                Console.WriteLine("Didn't expect to get here!");
            }
        }
        catch (WebException e)
        {
            WebResponse response = e.Response;
            using (StreamReader reader =
                        new StreamReader(response.GetResponseStream()))
            {
                string text = reader.ReadToEnd();
                Console.WriteLine(text);
            }
        }
    }
}
like image 160
Jon Skeet Avatar answered Dec 30 '25 15:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!