gpt4 book ai didi

c# - 无法使用 UTF8 编码转换 HttpResponseMessage

转载 作者:行者123 更新时间:2023-12-05 01:46:46 28 4
gpt4 key购买 nike

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

我的应用正在从 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);
}

关于c# - 无法使用 UTF8 编码转换 HttpResponseMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33563179/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com