HttpWebRequest StreamReader 失败,utf-8 不是受支持的编码名称错误
HttpWebRequest StreamReader fails with utf-8 is not a supported encoding name error
我正在使用以下代码从网页中检索数据。它在大多数页面中运行良好,但在某些页面中会抛出错误,如下所示;
String url = @"https://m.facebook.com";
try
{
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();
response.Close();
readStream.Close();
}
}
catch (Exception ex)
{
// utf-8 is not a supported encoding name error
}
如何解决这个问题?这里的其他帖子没有解决我的问题。
这里的错误是 response.CharacterSet
正在返回 "utf-8"
。方法 Encoding.GetEncoding
不知道这意味着什么,因为文本周围的引号。所以你必须把它们去掉。
替换此行:
readStream = new StreamReader(receiveStream,
Encoding.GetEncoding(response.CharacterSet));
这个:
readStream = new StreamReader(receiveStream,
Encoding.GetEncoding(response.CharacterSet.Replace("\"", string.Empty)));
我正在使用以下代码从网页中检索数据。它在大多数页面中运行良好,但在某些页面中会抛出错误,如下所示;
String url = @"https://m.facebook.com";
try
{
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();
response.Close();
readStream.Close();
}
}
catch (Exception ex)
{
// utf-8 is not a supported encoding name error
}
如何解决这个问题?这里的其他帖子没有解决我的问题。
这里的错误是 response.CharacterSet
正在返回 "utf-8"
。方法 Encoding.GetEncoding
不知道这意味着什么,因为文本周围的引号。所以你必须把它们去掉。
替换此行:
readStream = new StreamReader(receiveStream,
Encoding.GetEncoding(response.CharacterSet));
这个:
readStream = new StreamReader(receiveStream,
Encoding.GetEncoding(response.CharacterSet.Replace("\"", string.Empty)));