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

本文关键字:用户 密码 URL 读取 JSON | 更新日期: 2023-09-27 18:10:49

我使用的是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(内部服务器错误)。

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

你唯一错过的是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");