查询Comcast/Xfinity每月数据配额通过.NET/C#



以下代码报告"错误:未经身份验证"。

我如何使用.NET对此comcast/xfinity API进行身份验证以查询/获取用过的使用以及每月配额的帐户的可用数据?

static async Task Main() {
    using (var httpClient = new HttpClient()) {
        using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://customer.xfinity.com/apis/services/internet/usage")) {
            var response = await httpClient.SendAsync(request);
            var responseStream = await response.Content.ReadAsStreamAsync();
            var streamReader = new StreamReader(responseStream, Encoding.UTF8);
            var responseContent = streamReader.ReadToEnd(); // {"error":"unauthenticated"}
        }
    }
}

弄清楚了。该代码在.NET框架(测试4.7.1)或.NET Core(测试2.2)中运行。它使用其他定义的UsernamePassword值进行身份验证,并打印所使用的数据以及该月保留的数据。

static async Task Main() {
    using (var httpClient = new HttpClient()) {
        double totalUsage;
        double allowableUsage;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // this line can be removed in .NET Core
        using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://login.xfinity.com/login")) {
            var data = new Dictionary<string, string> {
                {"user", Username}
                , {"passwd", Password}
                , {"s", "oauth"}
                , {"continue", "https://oauth.xfinity.com/oauth/authorize?client_id=my-account-web&prompt=login&redirect_uri=https%3A%2F%2Fcustomer.xfinity.com%2Foauth%2Fcallback&response_type=code"}
            };
            var content = string.Join("&", data.Select(x => $"{x.Key}={WebUtility.UrlEncode(x.Value)}"));
            request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
            await httpClient.SendAsync(request);
        }
        using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://customer.xfinity.com/apis/services/internet/usage")) {
            var response = await httpClient.SendAsync(request);
            var responseStream = await response.Content.ReadAsStreamAsync();
            var streamReader = new StreamReader(responseStream);
            var responseContent = streamReader.ReadToEnd();
            var parsedResponse = JObject.Parse(responseContent);
            var usageMonths = parsedResponse["usageMonths"];
            var currentMonthUsage = usageMonths.Last;
            totalUsage = currentMonthUsage.Value<double?>("totalUsage") ?? 0;
            allowableUsage = currentMonthUsage.Value<double?>("allowableUsage") ?? 0;
        }
        Console.WriteLine($"Allowable: {allowableUsage}");
        Console.WriteLine($"Total    : {totalUsage}");
        Console.ReadKey();
    }
}

取决于nuget.org/packages/newtonsoft.json/12.0.1

相关内容

  • 没有找到相关文章

最新更新