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

时间:2017-11-14 10:02:25

标签: c# html asp.net-mvc

我正在试图从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;
        }

但是我遇到了下一个错误:''不是受支持的编码名称。

如果我尝试使用没有编码的html,我会得到下一个:‰PNG IHDR€L \öœgAMA±...

1 个答案:

答案 0 :(得分:2)

在这里,我有下载图像的方法:

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