using (WebResponse response = webRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string tmpStreamData = string.Empty;
while (!reader.EndOfStream)
{
while (reader.Peek() > -1)
{
tmpStreamData += (char)reader.Read();
}
}
MessageBox.Show(tmpStreamData);
}
}
有时我会在“tmpStreamData”中获得 符号。是否可以避免这种情况并以可读格式获取数据?
答案 0 :(得分:4)
// Get HTTP response. If this is not an HTTP response, you need to know the encoding yourself.
using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
{
// If not an HTTP response, then response.CharacterSet must be replaced by a predefined encoding, e.g. UTF-8.
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet)))
{
// Read whole stream to string.
string tmpStreamData = reader.ReadToEnd();
MessageBox.Show(tmpStreamData);
}
}