简体   繁体   English

无法获取编码-错误:“”不是受支持的编码名称

[英]Can't get encoding - error: “” is not a supported encoding name

I want get html from website using httpwebrequest. 我想使用httpwebrequest从网站获取html。 But with some website have error " is not a supported encoding name" . 但是在某些网站上出现错误“不是受支持的编码名称”。 Here is my code c#, thanks you. 这是我的代码c#,谢谢。

string url = textBox1.Text;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
    Stream receiveStream = response.GetResponseStream();
    StreamReader readStream = null;

    if (response.CharacterSet == null)
    {
        readStream = new StreamReader(receiveStream);
    }
    else
    {

        readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
    }

    string data = readStream.ReadToEnd();
    webBrowser1.Size = new System.Drawing.Size(0, 0);
    htmlview.Size = new System.Drawing.Size(800, 410);
    htmlview.Location = new Point(0, 3);
    htmlview.Margin = new Padding(3);

    htmlview.Text = data;
    response.Close();
    readStream.Close();
}

在此处输入图片说明

Most likely, the error occurs due to an invalid/unsupported encoding name. 最有可能是由于无效/不支持的编码名称而导致错误。 Please refer to here for more information. 请参考这里了解更多信息。

A possible solution to avoid such an exception is to check whether response.CharacterSet is a valid encoding name before creating the StreamReader. 避免此类异常的一种可能解决方案是在创建StreamReader之前检查response.CharacterSet是否为有效的编码名称。

Below is a modified version of your code: 下面是代码的修改版本:

            ...

            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream receiveStream = response.GetResponseStream();
                var encodingInfoNotFound = string.IsNullOrEmpty(response.CharacterSet) || !Encoding.GetEncodings().Any(e => e.Name == response.CharacterSet);
                var readStream = encodingInfoNotFound ? new StreamReader(receiveStream) : new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

                string data = readStream.ReadToEnd();
                ...
            }

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM