How to convert WebResponse.GetResponseStream return into a string?

梦想与她 提交于 2019-12-17 15:54:13

问题


I see many examples but all of them read them into byte arrays or 256 chars at a time, slowly. Why?

Is it not advisable to just convert the resulting Stream value into a string where I can parse it?


回答1:


You should create a StreamReader around the stream, then call ReadToEnd.

You should consider calling WebClient.DownloadString instead.




回答2:


You can use StreamReader.ReadToEnd(),

using (Stream stream = response.GetResponseStream())
{
   StreamReader reader = new StreamReader(stream, Encoding.UTF8);
   String responseString = reader.ReadToEnd();
}



回答3:


As @Heinzi mentioned the character set of the response should be used.

var encoding = response.CharacterSet == ""
    ? Encoding.UTF8
    : Encoding.GetEncoding(response.CharacterSet);

using (var stream = response.GetResponseStream())
{
    var reader = new StreamReader(stream, encoding);
    var responseString = reader.ReadToEnd();
}



回答4:


Richard Schneider is right. use code below to fetch data from site which is not utf8 charset will get wrong string.

using (Stream stream = response.GetResponseStream())
{
   StreamReader reader = new StreamReader(stream, Encoding.UTF8);
   String responseString = reader.ReadToEnd();
}

" i can't vote.so wrote this.




回答5:


You can create a StreamReader around the stream, then call StreamReader.ReadToEnd().

StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();


来源:https://stackoverflow.com/questions/7543324/how-to-convert-webresponse-getresponsestream-return-into-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!