亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

WebClient.DownloadString()返回帶有特殊字符的字符串

WebClient.DownloadString()返回帶有特殊字符的字符串

MMMHUHU 2019-12-03 16:48:32
我要從網絡上下載我正在構建的屏幕抓取工具的某些內容時遇到問題。在下面的代碼中,從Web客戶端下載字符串方法返回的字符串為一些(不是全部)網站的源下載返回一些奇數字符。我最近添加了http標頭,如下所示。以前,在沒有標題的情況下調用相同的代碼具有相同的效果。我沒有嘗試過'Accept-Charset'標頭的變體,除了基本知識之外,我對文本編碼了解不多。我指的字符或字符序列是:“ ??? ”和“ ? ”當您在Web瀏覽器中使用“查看源代碼”時,看不到這些字符。是什么原因造成的?我該如何解決該問題?string urlData = String.Empty;WebClient wc = new WebClient();// Add headers to impersonate a web browser. Some web sites // will not respond correctly without these headerswc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12");wc.Headers.Add("Accept", "*/*");wc.Headers.Add("Accept-Language", "en-gb,en;q=0.5");wc.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");urlData = wc.DownloadString(uri);
查看完整描述

3 回答

?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

???是八位位組的Windows-1252表示形式EF BB BF。這是UTF-8字節順序標記,這意味著您的遠程網頁是以UTF-8編碼的,但是您正在閱讀它的方式就像是Windows-1252。 根據該文檔,WebClient.DownloadString使用Webclient.Encoding它的編碼時,它的遠程資源轉換成字符串。設置為System.Text.Encoding.UTF8,理論上一切都會正常進行。


查看完整回答
反對 回復 2019-12-03
?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

WebClient.DownloadString實現的方式很笨。它應該從Content-Type響應的標題中獲取字符編碼,但是相反,它希望開發人員事先告知期望的編碼。我不知道此類的開發人員在想什么。


我創建了一個輔助類,該輔助類從Content-Type響應的頭中檢索編碼名稱:


public static class WebUtils

{

    public static Encoding GetEncodingFrom(

        NameValueCollection responseHeaders,

        Encoding defaultEncoding = null)

    {

        if(responseHeaders == null)

            throw new ArgumentNullException("responseHeaders");


        //Note that key lookup is case-insensitive

        var contentType = responseHeaders["Content-Type"];

        if(contentType == null)

            return defaultEncoding;


        var contentTypeParts = contentType.Split(';');

        if(contentTypeParts.Length <= 1)

            return defaultEncoding;


        var charsetPart =

            contentTypeParts.Skip(1).FirstOrDefault(

                p => p.TrimStart().StartsWith("charset", StringComparison.InvariantCultureIgnoreCase));

        if(charsetPart == null)

            return defaultEncoding;


        var charsetPartParts = charsetPart.Split('=');

        if(charsetPartParts.Length != 2)

            return defaultEncoding;


        var charsetName = charsetPartParts[1].Trim();

        if(charsetName == "")

            return defaultEncoding;


        try

        {

            return Encoding.GetEncoding(charsetName);

        }

        catch(ArgumentException ex) 

        {

            throw new UnknownEncodingException(

                charsetName,   

                "The server returned data in an unknown encoding: " + charsetName, 

                ex);

        }

    }

}

(這UnknownEncodingException是一個自定義的異常類,InvalidOperationException如果需要,可以隨意替換或其他)


然后,WebClient該類的以下擴展方法可以解決問題:


public static class WebClientExtensions

{

    public static string DownloadStringAwareOfEncoding(this WebClient webClient, Uri uri)

    {

        var rawData = webClient.DownloadData(uri);

        var encoding = WebUtils.GetEncodingFrom(webClient.ResponseHeaders, Encoding.UTF8);

        return encoding.GetString(rawData);

    }

}

因此,在您的示例中,您將執行以下操作:


urlData = wc.DownloadStringAwareOfEncoding(uri);

...就是這樣。


查看完整回答
反對 回復 2019-12-03
  • 3 回答
  • 0 關注
  • 1290 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號