Is it possible to get data from web response in a

2019-01-20 05:33发布

问题:

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

Sometimes I get � symbols in the "tmpStreamData". Is it possible to avoid such situations and get data in the readable format?

回答1:

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


标签: c# .net encoding