我遇到一个问题,服务向我返回 HTTP header :
Content-Type: application/json; charset=utf-16
当它被 C# 序列化时,它最终会出现在 UTF-8 流中,这显然会破坏。看来 utf-16 是 IANA spec 中的有效编码。那么为什么这段代码不起作用呢?
System.Net.Http.HttpClient httpClient ...;
using (var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
//response.Content.Headers.ContentType.CharSet = "utf-16"
using (var responseContentStream = await response.Content.ReadAsStreamAsync())
{
using (var streamReader = new StreamReader(stream))
{
//streamReader.CurrentEncoding.BodyName returns utf-8 here?!
}
}
}
所以最初响应
看起来很好,但是一旦到达streamReader
,它似乎就恢复为utf-8。为什么?
最佳答案
您可以在构造函数中指定 StreamReader 应使用的编码。 在你的情况下,它应该看起来像这样:
using (var streamReader = new StreamReader(stream, Encoding.Unicode, true))
{
// The reader should read the Stream with UTF-16 here
}
关于c# - 为什么这个 UTF-16 HTTP 响应在生成的流中最终变成 UTF-8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63052689/