【问题标题】:C# .Net6 HTTPClient - Character problemsC# .Net6 HTTPClient - 字符问题
【发布时间】:2022-01-04 11:28:36
【问题描述】:

我在使用 HTTPCLient 时遇到了一些字符问题,它必须出现在
出现 \u003cBR\u003e,我必须解决这个问题,我必须使用 .Replace("\u003c", "")?

我使用的是下面的代码吗?

 using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add(header,
                    headerAuthenticationValue);
                
                using (HttpResponseMessage response = await client.GetAsync(url))
                {
                    using (HttpContent content = response.Content)
                    {
                        var tmpStr = await content.ReadAsStringAsync();
                    }
                }
            }

【问题讨论】:

  • using (HttpClient client = new HttpClient()) Read the docs "HttpClient 旨在被实例化一次并在应用程序的整个生命周期中重复使用。为每个请求实例化 HttpClient 类将耗尽重负载下可用的套接字数量。这将导致 SocketException 错误。 "
  • 无论如何。你的实际问题是什么?您收到的数据不是您想要的格式吗?我认为这不是 HttpClient 的问题,而是数据源的问题。它似乎是 unicode ,也许您缺少一些 json 序列化程序?还是其他解码器?来源是什么?
  • 感谢使用提示(HttpClient client = new HttpClient())。我正在将我的代码 .Net Frameworks 4.7.2 更新到 .Net 6 并且在信息正确出现之前。文本是:Peças e Acessórios Originais ARNO
    Redutor Completo 它即将推出:Peças e Acessórios Originais ARNO\\u003cBR\\u003eRedutor Completo 另一个改变是,在我使用 Visual Studio 2019 和 Windows10 之前,现在我'我在 Ubuntu 上使用 VSCode,我开始在 Ubuntu 上迁移,但我认为这不是问题。
  • 如何获取源码?这看起来像双重编码。通常\u003c 会解析为 unicode 字符,但由于 \ 被额外的 \ 转义,因此无法正确解析。

标签: c#


【解决方案1】:

您收到一个字符串,其中包含表示 HTML 字符的转义 Unicode 字符。你可以使用WebUtility.HtmlDecode:

var str = WebUtility.HtmlDecode("\u003cBR\u003e"); // returns <BR>

或者在你的情况下:

var tmpStr = WebUtility.HtmlDecode(await content.ReadAsStringAsync());

【讨论】:

  • \u003c 不是 HTML 字符,而是 unicode。此外,他实际上正在接收\\u003c
  • 这是 HTML 字符 &lt; 的转义 unicode 表示,并使用 WebUtility.HtmlDecode 正确替换它:) 目前尚不清楚他们是否收到\u003c(如问题中所述)或\\u003c (如他们的评论所述)。
  • 恕我直言,这就像使用螺丝刀的后端驱动钉子一样...... HtmlDecode 是解码一个已经被html编码的字符串,而不是修复其他可以解决的问题更好的方法。
  • 我收到了\\u003c,奇怪的是当我使用代码时:var request = HttpWebRequest.Create(url); request.ContentType = "应用程序/json"; request.Method = "GET"; request.Headers.Add(header, headerAuthenticationValue);使用 (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { var tmpStr = eader.ReadToEnd();在 .Net Frameworks 4.7.2 中它可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-14
  • 1970-01-01
相关资源
最近更新 更多