可以';t使用UTF8编码转换HttpResponseMessage

本文关键字:UTF8 编码 转换 HttpResponseMessage 使用 可以 | 更新日期: 2023-09-27 18:20:53

我正在努力解决常见的转换问题,但不幸的是,我还没能找到任何解决我特定问题的方法。

我的应用程序正在从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个字符。

我还读过一些答案,比如如何将UTF-8字符串转换为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方法工作得很好,问题是当我使用响应消息时。

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

可以';t使用UTF8编码转换HttpResponseMessage

我自己解决了这个问题。我发现服务器响应是一个utf-8json的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);