HttpClient在UWP app

时间:2017-07-14 12:44:41

标签: c# uwp dotnet-httpclient

我有一个常规的.NET Framework类库,可以成功调用Twitter REST API并返回从API返回的JSON数据。

此库已复制到通用Windows类库中的UWP应用程序。所有东西都是开箱即用的(除了一些小的命名空间更改)。

然而,从UWP库返回的数据只是垃圾! .NET框架库返回JSON数据,而UWP库在Visual Studio中返回如下所示的内容:

  

\ u001f?\ b \ 0 \ 0 \ 0 \ 0 \ 0 \ 0?Vmo?6 \ u0010?+ ....

有些问题看似相似,like this one,但是(和其他答案)使用的ReadAsBufferAsync在我的库中返回的HttpResponseMessage中不存在。

如何让我的UWP库的工作方式与我的框架库相同?

这是我的HttpClient用法,对于UWP和Framework库都是相同的:

using (HttpClient client = new HttpClient()) {
    client.BaseAddress = new Uri(TWITTER_API);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("Authorization", generatedAuthString);

    HttpResponseMessage response = await client.GetAsync(TWITTER_API_PATH);
    if (response.StatusCode == HttpStatusCode.OK) {
        // This returns garbage in UWP library, correct JSON string in Framework library
        return await response.Content.ReadAsStringAsync();
    }

    return null;
}

我还尝试使用ReadAsByteArrayAsync()然后使用Encoding.UTF8.GetString(),但它产生了相同的垃圾结果。

这些是API调用返回的响应头:

server: tsa_o
strict-transport-security: max-age=631138519
x-transaction: 00ba702600ece624
x-connection-hash: 4f6ae39419ed099fbc9eaa61419071ee
x-twitter-response-tags: BouncerCompliant
cache-control: no-store, must-revalidate, no-cache, pre-check=0, post-check=0
x-rate-limit-remaining: 899
set-cookie: lang=en; Path=/, guest_id=v1%3A150003721463912535; Domain=.twitter.com; Path=/; Expires=Sun, 14-Jul-2019 13:00:14 UTC
x-rate-limit-limit: 900
date: Fri, 14 Jul 2017 13:00:14 GMT
x-response-time: 199
x-frame-options: SAMEORIGIN
x-rate-limit-reset: 1500038114
status: 200 OK
x-content-type-options: nosniff
x-access-level: read-write-directmessages
pragma: no-cache
x-xss-protection: 1; mode=block

0 个答案:

没有答案