gpt4 book ai didi

c# - HttpWeb 请求错误 : 503 server unavailable

转载 作者:太空狗 更新时间:2023-10-29 21:06:06 25 4
gpt4 key购买 nike

我正在使用 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;
}

最佳答案

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

您可以访问异常的 Response 属性中的响应(如果有 503 响应,引发的异常是 WebException,它有一个 响应属性)。你需要捕获这个异常并妥善处理它

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

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;

关于c# - HttpWeb 请求错误 : 503 server unavailable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10107305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com