无法使用 UTF8 编码转换 HttpResponseMessage

Can't convert HttpResponseMessage with UTF8 encoding

我正在为常见的转换问题苦苦挣扎,但不幸的是,我找不到任何适合我的特定问题的东西。

我的应用正在从 php 服务器接收 System.Net.Http.HttpResponseMessage,UTF8 编码,包含一些字符,例如 \u00c3\u00a0 (à),我无法转换它们。

string message = await result.Content.ReadAsStringAsync();
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
string newmessage = Encoding.UTF8.GetString(messageBytes, 0, messageBytes.Length);

这只是我的尝试之一,但没有任何反应,结果字符串仍然有 \u00c3\u00a0 个字符。

我也阅读了一些答案,例如 How to convert a UTF-8 string into Unicode?,但此解决方案对我不起作用。这是解决方案代码:

public static string DecodeFromUtf8(this string utf8String)
{
   // copy the string as UTF-8 bytes.
   byte[] utf8Bytes = new byte[utf8String.Length];
   for (int i=0;i<utf8String.Length;++i) {
      //Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
      utf8Bytes[i] = (byte)utf8String[i];
   }

   return Encoding.UTF8.GetString(utf8Bytes,0,utf8Bytes.Length);
}

DecodeFromUtf8("d\u00C3\u00A9j\u00C3\u00A0"); // déjà

我注意到,当我使用像

这样的简单字符串尝试上述解决方案时
string str = "Comunit\u00c3\u00a0"

DecodeFromUtf8 方法工作得很好,问题是当我使用我的响应消息时。

如有任何建议,我们将不胜感激

我自己解决了这个问题。我发现服务器响应是 utf-8 json 的 ISO 字符串,所以我不得不删除 json 转义字符,然后将 iso 转换为 utf8

所以我必须执行以下操作:

private async Task<string> ResponseMessageAsync(HttpResponseMessage result)
{
    string message = await result.Content.ReadAsStringAsync();
    string parsedString = Regex.Unescape(message);
    byte[] isoBites = Encoding.GetEncoding("ISO-8859-1").GetBytes(parsedString);
    return Encoding.UTF8.GetString(isoBites, 0, isoBites.Length);
 }

我的作品变化自:

string message = await result.Content.ReadAsStringAsync();
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
string newmessage = Encoding.UTF8.GetString(messageBytes, 0, messageBytes.Length);

至:

byte[] bytes = await result.Content.ReadAsByteArrayAsync();
Encoding utf8 = Encoding.UTF8;
string newmessage = utf8.GetString(bytes);