我想使用httpwebrequest从网站获取html。但是在某些网站上出现错误“不是受支持的编码名称”。这是我的代码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();
}
答案 0 :(得分:0)
很可能是由于无效/不支持的编码名称而导致的错误。有关更多信息,请参阅here。
避免此类异常的一种可能解决方案是在创建StreamReader之前检查response.CharacterSet
是否为有效的编码名称。
下面是代码的修改版本:
...
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();
...
}
希望有帮助。