什么是阅读GetResponseStream()的最佳方法是什么? [英] What is the best way to read GetResponseStream()?

查看:1316
本文介绍了什么是阅读GetResponseStream()的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我不太清楚这是否是最有效的方式来读取一个HTTP响应。

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

我需要作为字符串输出,我看到一个文章用不同的方法,但我不太如果它是一个很好的一个。在我的测试,code有一些编码问题,在不同的网站。

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.

你怎么看网上的反应?

推荐答案

我用这样的下载从URL文件:

I use something like this to download a file from a 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;
}

这篇关于什么是阅读GetResponseStream()的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆