读取GetResponseStream()的最佳方法是什么?

时间:2020-03-06 14:45:39  来源:igfitidea点击:

从GetResponseStream读取HTTP响应的最佳方法是什么?

目前,我正在使用以下方法。

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

我不太确定这是否是读取http响应的最有效方法。

我需要将输出作为字符串,我看过一篇使用不同方法的文章,但是如果它是一个很好的文章,我还不太清楚。在我的测试中,该代码在不同的网站上存在一些编码问题。

我们如何阅读网络回复?

解决方案

我使用类似的方法从URL下载文件:

if (!Directory.Exists(localFolder))
{
    Directory.CreateDirectory(localFolder);   
}

try
{
    HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(Path.Combine(uri, filename));
    httpRequest.Method = "GET";

    // if the URI doesn't exist, an exception will be thrown here...
    using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
    {
        using (Stream responseStream = httpResponse.GetResponseStream())
        {
            using (FileStream localFileStream = 
                new FileStream(Path.Combine(localFolder, filename), FileMode.Create))
            {
                var buffer = new byte[4096];
                long totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    totalBytesRead += bytesRead;
                    localFileStream.Write(buffer, 0, bytesRead);
                }
            }
        }
    }
}
catch (Exception ex)
{
    // You might want to handle some specific errors : Just pass on up for now...
    // Remove this catch if you don't want to handle errors here.
    throw;
}

我们忘记定义"缓冲区"和" totalBytesRead":

using ( FileStream localFileStream = ....  
{  
    byte[] buffer = new byte[ 255 ];  
    int bytesRead;  
    double totalBytesRead = 0;  

    while ((bytesRead = ....

也许我们可以研究WebClient类。这是一个例子:

using System.Net;

namespace WebClientExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var remoteUri = "http://www.contoso.com/library/homepage/images/";
            var fileName = "ms-banner.gif";
            WebClient myWebClient = new WebClient();
            myWebClient.DownloadFile(remoteUri + fileName, fileName);
        }
    }
}

我对字符串做的简单方法。注意StreamReader构造函数上的true第二个参数。这告诉它从字节顺序标记中检测编码,并且可能也有助于解决我们遇到的编码问题。

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