HTTPClient返回HttpRequestException WinRT

时间:2013-02-17 20:21:13

标签: c# json windows-runtime httpclient

出于某种原因,当我尝试从我正在使用的Web API获取JSON结果时,我在Visual Studio中收到 403:禁止异常。当我在网络浏览器中尝试使用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; }
    }

}

1 个答案:

答案 0 :(得分: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();