【问题标题】:Windows.Web.Http.HttpClient character encodingWindows.Web.Http.HttpClient 字符编码
【发布时间】:2016-01-29 21:11:14
【问题描述】:

所以我正在尝试读取包含捷克字符(ř、ť、š、ň 等)的页面的 HTML 源代码。页面的字符集是windows-1250 (Content-type = text/html; charset=windows-1250)。

    var hc = new Windows.Web.Http.HttpClient();
    var uri = new Windows.Foundation.Uri("http://rozvrhuni.hys.cz/150909.html");
    hc.defaultRequestHeaders.acceptLanguage.parseAdd("cs");
    hc.defaultRequestHeaders.acceptEncoding.parseAdd("windows-1250");
    hc.getStringAsync(uri).done(
        function complete(result) {
            htmlText = result;
        },
        function error(result) {
            (new Windows.UI.Popups.MessageDialog("Non-existent content", "Error")).showAsync().done();
            return;
        }
    );

我的代码获得了源代码,但继续读错一些字符(ř = ø、č = è 等)

如何正确阅读页面?

【问题讨论】:

    标签: javascript character-encoding winjs uwp


    【解决方案1】:

    我不熟悉 JavaScript,但我相信这个概念与 C# 相同。

    以下代码是用 C# 编写的,但我希望它对您有所帮助。

    string retVal = "";
    byte[] bodybytes = {0};
    
    // This 'RegisterProvider' call is enough at once per process.
    var provider = System.Text.CodePagesEncodingProvider.Instance;
    System.Text.Encoding.RegisterProvider(provider);
    
    var enc = Encoding.GetEncoding("windows-1250");
    ...
    bodybytes = await response.Content.ReadAsByteArrayAsync();
    ...
    retVal = enc.GetString(bodybytes, 0, bodybytes.Length);
    

    注意 - 您可能需要将以下 nuget 包添加到您的项目中。 https://www.nuget.org/packages/System.Text.Encoding.CodePages/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-31
      • 2011-03-02
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      相关资源
      最近更新 更多