在WebHttpRequest請求網頁后,獲取到的中文是亂碼,類似這樣:
<title>˹ŵ��Ϸ���������� - ��̳������ - ˹ŵ��Ϸ����</title>
原因是網頁多種編碼方式(上述charset=gbk),UWP中Encoding能夠支持UTF-8、Unicode,但是不支持gb2312、gbk等編碼。
因此我們需要在獲取流的時候對編碼方式進行處理。
var reader = new StreamReader(stream, Encoding.GetEncoding("UTF-8")); //UTF-8編碼
網上搜到WP8下的解決方法,但是不能夠直接用於UWP中,需要修改:
http://encoding4silverlight.codeplex.com/ 下載
找到DBCD下的三個文件,將他們添加到解決方案中
1.DBCSEncoding.cs 2.Maps\big5.bin 3.gb2312.bin
【原方案:將兩個.bin文件設置為嵌入的資源,將DBCSEncoding.cs設置為編譯】
但你會發現:這條代碼報錯,意思是獲取.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);
}
