Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpWebRequest.GetResponse methods throws 404 exception

I want to download one image from url using console application.

I have used following code:

string sourceUrl = "http://i.ytimg.com/vi/pvBnYBsUi9A/default.jpg"; // Not Found
                //string sourceUrl = "http://i.ytimg.com/vi/OrxZAN1FZUY/default.jpg"; // Found
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sourceUrl);
                HttpWebResponse response = null;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (Exception)
                {

                }

Above code throws exception in line "response = (HttpWebResponse)request.GetResponse();"

but when I am accessing "http://i.ytimg.com/vi/pvBnYBsUi9A/default.jpg" url in my browser then image will be display.

What I am missing here?

like image 906
Kalpesh Vaghela Avatar asked Oct 31 '22 03:10

Kalpesh Vaghela


1 Answers

I tried that url "http://i.ytimg.com/vi/pvBnYBsUi9A/default.jpg" in Chrome developer tools. It also receives a 404, but the response includes the image, which displays.

Your code is not the cause of the exception. The site is returning a 404 and your code gets an exception.

You could write logic to look at the response even if you get a 404 and decide whether to take it anyway, as the browser does.

It looks like you can get the response returned by the site if you catch WebException, which allows you to see the http request status and the response, per the documentation.

Example from the .Net 4.5 doc...

try 
      { 
            // Creates an HttpWebRequest for the specified URL. 
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
            // Sends the HttpWebRequest and waits for a response.
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 
            if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
               Console.WriteLine("\r\nResponse Status Code is OK and StatusDescription is: {0}",
                                    myHttpWebResponse.StatusDescription);
            // Releases the resources of the response.
            myHttpWebResponse.Close(); 

        } 
    catch(WebException e) 
       {
            Console.WriteLine("\r\nWebException Raised. The following error occured : {0}",e.Status); 
       }
    catch(Exception e)
    {
        Console.WriteLine("\nThe following Exception was raised : {0}",e.Message);

WebException has Response and Status properties. So it looks like the .Net way to deal with this is to catch WebException and determine how to handle based on the status and response content (if necessary).

like image 162
joshp Avatar answered Nov 10 '22 11:11

joshp