简体   繁体   English

从c#读取html,''不是受支持的编码名称错误

[英]read html from c#, '' is not a supported encoding name error

i'm triying to read a html from c# like this: 我正在尝试从C#中读取HTML,如下所示:

      public string getHTMLIcon() {
            string url = @"http://ddragon.leagueoflegends.com/cdn/7.5.1/img/profileicon/1258.png";
            string data = string.Empty;

            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));
                }

                data = readStream.ReadToEnd();

                response.Close();
                readStream.Close();
            }
            return data;
        }

But is getting me the next error: '' is not a supported encoding name. 但是让我遇到下一个错误:”不是受支持的编码名称。

If i try get the html without the encoding i get the next: ‰PNG IHDR€€L\\öœgAMA± ... 如果我尝试获取不带编码的html,则会得到下一个:‰PNG IHDR€L \\öœgAMA±...

Here you have my methods for downloading an image: 在这里,您有我下载图像的方法:

        public static Stream DownloadImage(string url, string referer)
        {
            try
            {
                var u = new Uri(url);
                HttpWebRequest request;

                request = (HttpWebRequest)WebRequest.Create(u);

                request.Referer = referer;
                request.UserAgent = "userAgent";

                var response = (HttpWebResponse)request.GetResponse();
                if (response != null)
                {
                    return response.GetResponseStream();
                }
            }
            catch (WebException wex)
            {
                Logging.Write($"WEB ERROR {url} \n" + wex.Message);
                throw;
            }

            return null;
        }

    public static void DownloadImage(string url, string referer, string localFilePath)
    {
        Stream stream = DownloadImage(url, referer);

        using(FileStream file = File.Create(localFilePath))
        {
            stream.CopyTo(file);
        }
    }

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

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