HttpWebRequest error: no server 503

I am using HttpWebRequest and I get an error while executing GetResponse ().

I am using this code:

private void button1_Click(object sender, EventArgs e) { Uri myUri = new Uri("http://www.google.com/sorry/?continue=http://www.google.com/search%3Fq%3Dyamaha"); // Create a 'HttpWebRequest' object for the specified url. HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri); // Set the user agent as if we were a web browser myHttpWebRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4"; HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); var stream = myHttpWebResponse.GetResponseStream(); var reader = new StreamReader(stream); var html = reader.ReadToEnd(); // Release resources of response object. myHttpWebResponse.Close(); textBox1.Text = html; } 
+6
source share
1 answer

The server does return an HTTP status code of 503. However, it also returns the response body along with error condition 503 (the content that you see in the browser if you open this URL).

You have access to the response in the exception Response property (in the case of response 503, the exception that was WebException is a WebException that has the Response property). you need to catch this exception and handle it correctly

Specifically, your code might look like this:

 string html; try { var myUri = new Uri("http://www.google.com/sorry/?continue=http://www.google.com/search%3Fq%3Dyamaha"); // Create a 'HttpWebRequest' object for the specified url. var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri); // Set the user agent as if we were a web browser myHttpWebRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4"; var myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); var stream = myHttpWebResponse.GetResponseStream(); var reader = new StreamReader(stream); html = reader.ReadToEnd(); // Release resources of response object. myHttpWebResponse.Close(); } catch (WebException ex) { using(var sr = new StreamReader(ex.Response.GetResponseStream())) html = sr.ReadToEnd(); } textBox1.Text = html; 
+11
source

Source: https://habr.com/ru/post/912938/


All Articles