.NET Core中使用編碼GB2312報錯‘GB2312‘ is not a supported encoding name解決方案

前言

今天在.Net Core中對外網新聞進行爬蟲抓取,最初抓取到的新聞中出現了亂碼,後來通過GB2312進行了編碼,結果報錯“ Unhandled Exception: System.ArgumentException: 'GB2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.”。

報錯信息 
爲了解決中文亂碼問題,使用瞭如下代碼

byte[] response1 = await client.GetByteArrayAsync(url1);
string temp = Encoding.GetEncoding("GB2312").GetString(response1);
 報錯如下

Unhandled Exception: System.ArgumentException: 'GB2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.

解決方案 
1、在NuGet包中安裝包System.Text.Encoding.CodePages

2、在使用編碼方法(Encoding.GetEncoding("GB2312"))之前,對編碼進行註冊( Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);),代碼如下 

var url1 = "需要抓取新聞列表的url";
//以byte[]獲取html
byte[] response1 = await client.GetByteArrayAsync(url1);
//將byte[]重新編碼成GB2312;
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
string temp = Encoding.GetEncoding("GB2312").GetString(response1);
修改完成後重新編譯成功

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章