HttpWebRequest Error: 503 server unavailable

2019-04-28 22:08发布

问题:

I'm using HttpWebRequest and I get error when execute GetResponse().

I 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;
    }

回答1:

The server really returns a 503 HTTP status code. However, it also returns a response body along with the 503 error condition (the contents you see in a browser if you open that URL).

You have access to the response in the exception's Response property (in case there's a 503 response, the exception that's raised is a WebException, which has a Response property). you need to catch this exception and handle it properly

Concretely, your code could 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;