HttpWebRequest.GetResponse Methods Throw 404 Exception

I want to load a single image from url using a console application.

I used the 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)
                {

                }

The above code throws an exception in the line "response = (HttpWebResponse) request.GetResponse ();"

but when I access the http://i.ytimg.com/vi/pvBnYBsUi9A/default.jpg "url in my browser, then the image will be displayed.

What am I missing here?

+4
source share
1 answer

I tried this url " http://i.ytimg.com/vi/pvBnYBsUi9A/default.jpg " in Chrome developer tools. It also gets 404, but the response includes an image that is displayed.

. 404, .

, , 404 , , .

, , , WebException, HTTP- .

.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 Response Status. , , .Net- - WebException , ( ).

+1

All Articles