Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

.net - What is the best way to read GetResponseStream()?

What is the best way to read an HTTP response from GetResponseStream ?

Currently I'm using the following approach.

Using SReader As StreamReader = New StreamReader(HttpRes.GetResponseStream)
   SourceCode = SReader.ReadToEnd()
End Using

I'm not quite sure if this is the most efficient way to read an http response.

I need the output as string, I've seen an article with a different approach but I'm not quite if it's a good one. And in my tests that code had some encoding issues with in different websites.

How do you read web responses?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

My simple way of doing it to a string. Note the true second parameter on the StreamReader constructor. This tells it to detect the encoding from the byte order marks and may help with the encoding issue you are getting as well.

string target = string.Empty;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=583");

HttpWebResponse response = (HttpWebResponse)httpWebRequest.GetResponse();
try
{
  StreamReader streamReader = new StreamReader(response.GetResponseStream(),true);                
  try
  {
    target = streamReader.ReadToEnd();
  }
  finally
  {
    streamReader.Close();
  }
}
finally
{
  response.Close();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...