2

出于某种原因,当我尝试从我正在使用的 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; }
    }

}
4

1 回答 1

2

如果您使用默认用户代理,服务器似乎会响应您 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();
于 2013-02-18T02:05:14.600 回答