問題描述
我正在構建一個 Windows 應用商店應用,但我一直無法從 API 獲得 UTF-8 響應.
I'm building a Windows Store app, but I'm stuck at getting a UTF-8 response from an API.
這是代碼:
using (HttpClient client = new HttpClient())
{
Uri url = new Uri(BaseUrl + "/me/lists");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Add("Accept", "application/json");
HttpResponseMessage response = await client.SendRequestAsync(request);
response.EnsureSuccessStatusCode();
string responseString = await response.Content.ReadAsStringAsync();
response.Dispose();
}
reponseString
總是包含奇怪的字符,應該是像 é 這樣的重音符號,我嘗試使用流,但我在一些示例中找到的 API 不存在于Windows RT.
The reponseString
always contains strange characters which should be accents like é, and I tried using a stream, but the API I found in some examples don't exist in Windows RT.
改進的代碼,仍然是同樣的問題.
improved code, still same problem.
推薦答案
你可以使用 response.Content.ReadAsBufferAsync()
而不是直接使用 response.Content.ReadAsStringAsync()
@Kiewic 指向的代碼> 如下:
Instead of using response.Content.ReadAsStringAsync()
directly you could use response.Content.ReadAsBufferAsync()
pointed by @Kiewic as follows:
var buffer = await response.Content.ReadAsBufferAsync();
var byteArray = buffer.ToArray();
var responseString = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
這在我的情況下有效,我想使用 UTF8 應該可以解決大部分問題.現在想想為什么沒有辦法使用 ReadAsStringAsync
來做到這一點:)
This is working in my case and I guess that using UTF8 should solve most of the issues. Now go figure why there is no way to do this using ReadAsStringAsync
:)
這篇關于在 Windows 應用商店應用程序中使用 httpclient 獲取 UTF-8 響應的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!