C# HttpWebRequest错误:503服务器不可用

C# HttpWebRequest错误:503服务器不可用,c#,https,httpwebrequest,C#,Https,Httpwebrequest,我正在使用HttpWebRequest,执行GetResponse()时出错 我使用此代码: 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 'HttpWebRe

我正在使用HttpWebRequest,执行GetResponse()时出错

我使用此代码:

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

服务器实际上返回一个503HTTP状态代码。但是,它还返回一个响应正文以及503错误条件(如果打开该URL,则在浏览器中看到的内容)

您可以访问异常的
response
属性中的响应(如果有503响应,则引发的异常是
WebException
,它具有
response
属性)。您需要捕获此异常并正确处理它

具体来说,您的代码可以如下所示:

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;

在浏览器或类似于curl的工具中请求URL时,您是否遇到了相同的错误?这看起来是一个以编程方式获取的非常奇怪的URL。有什么原因吗?返回一个503。如果你正试图自动化大量的谷歌查询,你可能会得到这个URL。但是,正如Jon Skeet所问的,为什么您首先要向该URL提交请求?请参阅Google检测到您正在尝试获取一个并非以编程方式获取的URL。你为什么要获取那个URL?@Ainun Nuha我正在尝试将文本从泰国翻译成英语,但我面临着类似的问题。我在GetResponse()处得到异常,它在catch()块中被捕获。但它发送包含“网页被阻止”内容的完整页面的HTML。如何将字符串翻译成英语。