从URL读取JSON并传递用户名和密码

时间:2013-04-24 06:13:22

标签: c# json httpclient winrt-xaml

我正在使用WinRT框架。我必须通过传递用户名和密码从服务URL获得JSON响应。

这是我试过的代码

var credentials = new NetworkCredential("***", "***");
        var handler = new HttpClientHandler { Credentials = credentials };
        //client.DefaultRequestHeaders.Add("UserID", "****");
        //client.DefaultRequestHeaders.Add("Password", "****");
        HttpClient client = new HttpClient(handler);

但是这个抛出错误

响应状态代码不表示成功:500(内部服务器错误)。

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

你唯一遗漏的是User-Agent。这有效....

var credentials = new NetworkCredential("****", "*****");
var handler = new HttpClientHandler { Credentials = credentials, AllowAutoRedirect = true };

HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Add("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12"); 
var responseString = await client.GetStringAsync("https://mobility.gap.com/MobileAppProvider/resources/gapresources/v1/buildings");