gpt4 book ai didi

c# - HTTPClient 返回 HttpRequestException WinRT

转载 作者:太空宇宙 更新时间:2023-11-03 11:08:29 25 4
gpt4 key购买 nike

出于某种原因,当我尝试从我正在使用的 Web API 中获取 JSON 结果时,我在 Visual Studio 中收到了 403: Forbidden 异常。当我尝试在我的 Web 浏览器中使用 Web API URL 时,一切都按预期显示。有任何想法吗?

主要代码:

        theURI = "http://isitup.org/duckduckgo.com.json";
HttpClient httpClient = new HttpClient();
httpClient.MaxResponseContentBufferSize = Int32.MaxValue;
var jsonResponse = await httpClient.GetStringAsync(theURI);

var rootObject = JsonConvert.DeserializeObject<StatusMessage.RootObject>(jsonResponse);
int statuscode = rootObject.status_code;

if (statuscode == 1)
{
txtStatus.Text = "Website is UP!";
}
else if (statuscode == 2)
{
txtStatus.Text = "Website is DOWN!";
}
else
{
txtStatus.Text = "Invalid domain!";
}

和类文件

class StatusMessage
{
public class RootObject
{
public string domain { get; set; }
public int port { get; set; }
public int status_code { get; set; }
public object response_ip { get; set; }
public object response_code { get; set; }
public object response_time { get; set; }
}

}

最佳答案

如果您使用的是默认用户代理,服务器似乎会响应您 403。如果您将其更改为 chrome 用户代理,则服务器会正​​确响应。

var url = new Uri("http://isitup.org/duckduckgo.com.json");
var req = new HttpClient();
var message = new HttpRequestMessage(HttpMethod.Get, url);
message.Headers.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17");
var response = await req.SendAsync(message);
var responseString = await response.Content.ReadAsStringAsync();

关于c# - HTTPClient 返回 HttpRequestException WinRT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14925643/

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