【UWP】解析GB23十二、GBK編碼網頁亂碼問題

在WebHttpRequest請求網頁後,獲取到的中文是亂碼,相似這樣:windows

<title>˹ŵ��Ϸ���������� - ��̳������ -  ˹ŵ��Ϸ����</title>       app

緣由是網頁多種編碼方式(上述charset=gbk),UWP中Encoding可以支持UTF-八、Unicode,可是不支持gb23十二、gbk等編碼。async

所以咱們須要在獲取流的時候對編碼方式進行處理。編碼

var reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8"));  //UTF-8編碼spa

 

網上搜到WP8下的解決方法,可是不可以直接用於UWP中,須要修改:code

http://encoding4silverlight.codeplex.com/   下載component

找到DBCD下的三個文件,將他們添加到解決方案中資源

1.DBCSEncoding.cs       2.Maps\big5.bin       3.gb2312.bin get

【原方案:將兩個.bin文件設置爲嵌入的資源,將DBCSEncoding.cs設置爲編譯】string

但你會發現:這條代碼報錯,意思是獲取.bin文件的流:

Stream stream = typeof(DBCSEncoding).Assembly.GetManifestResourceStream(typeof(DBCSEncoding).Assembly.GetManifestResourceNames().Single(s => s.EndsWith("." + name + ".bin")))

是由於Type類型找不到Assembly屬性;

因而想到用Application.GetResourceStream(uri)的方式取得.bin文件,可是UWP中沒有了這個API了。

又查到以下:

http://msdn.microsoft.com/en-us/library/windows/apps/xaml/br229571.aspx 其中的Application object and app model 的最後一點:

Silverlight apps could either package application parts into the deployment package, as external parts, or download components on demand. A Metro style app has these choices too, but the APIs used to access the package parts are different. Where Silverlight uses Application.GetResourceStream, a Metro style app uses a more generalized model, where the installed package is just a storage folder. For example, you can call Package.InstalledLocation and then call a variety of StorageFolder APIs (most of which are async) in order to get any other packaged components.

意思是說Application.GetResourceStream的對應方式是經過Package.InstalledLocation 拿到安裝目錄,而後經過文件操做去讀取資源。

 

因此就來看看如何操做:我把.bin放在另外一個叫作DataHelperLib的Maps文件夾裏。

固然你須要吧.bin的生成操做設置爲內容,安裝包裏面纔會出現

  public async static Task<Stream> GetInstall()

  {

    //此處只是簡單的獲取到gb2312.bin文件

    var folderInstall = Windows.ApplicationModel.Package.Current.InstalledLocation;  //獲取安裝包的位置

            var folder = await folderInstall.GetFolderAsync("DataHelperLib");  //獲取DataHelperLib文件夾

            var mapFolder = await folder.GetFolderAsync("Maps");  //獲取Maps文件夾

            var file = await mapFolder.GetFileAsync("gb2312.bin");  //獲取gb2312.bin

            Stream stream = await file.OpenStreamForReadAsync();  //獲取文件流

             return stream;

  }

以後將DBCSEncoding.cs錯誤的那條代碼替換成

  using(Stream stream = await StorageHelper.GetInstall());  //別忘了將方法的返回值改成Task<DBCSEncoding>

最後以這種編碼方式讀取流:

  using (var stream = response.GetResponseStream())  {    var reader = new StreamReader(stream, await DBCSEncoding.GetDBCSEncoding("GB2312"));    string content = reader.ReadToEnd();    //DoSomething with callback stream    OnSuccess(content, response.StatusCode);  }

相關文章
相關標籤/搜索