2012-04-11 296 views
6

我正在使用HttpWebRequest,并且在执行GetResponse()时出现错误。HttpWebRequest错误:503服务器不可用

我使用此代码:

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

你得到同样的错误,要求在浏览器的URL或像curl这样的工具是什么时候? – jlafay 2012-04-11 13:51:57

+1

这看起来像一个绝对奇怪的URL以编程方式获取。任何理由吗? – 2012-04-11 13:52:04

+1

http://www.google.com/sorry/返回503.如果您尝试自动化大量的Google查询,则可能会获得该网址。但正如Jon Skeet所问,为什么你首先向这个URL提交请求?请参阅http://support.google.com/websearch/bin/answer.py?hl=zh-CN&answer=86640 – 2012-04-11 13:53:16

回答

11

服务器确实返回503 HTTP状态代码。但是,它也会返回一个响应主体以及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; 
+0

此代码工作..非常感谢你 – 2012-04-12 12:22:12

+1

@Ainun Nuha我正在尝试将文本从泰国翻译成英文,但我面临类似的问题。我在catch()块中捕获的GetResponse()中得到异常。但它发送的内容为“Web Page Blocked”的完整页面的HTML。我怎样才能将字符串翻译成英文。 – RSB 2016-09-22 10:55:02

相关问题