.net 阅读 GetResponseStream() 的最佳方式是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/137285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best way to read GetResponseStream()?
提问by
What is the best way to read an HTTP response from GetResponseStream ?
从 GetResponseStream 读取 HTTP 响应的最佳方法是什么?
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.
我不太确定这是否是读取 http 响应的最有效方式。
I need the output as string, I've seen an articlewith 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?
您如何阅读网络回复?
回答by Mitch Wheat
I use something like this to download a file from a URL:
我使用这样的东西从 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;
}
回答by Andrei R?nea
Maybe you could look into the WebClientclass. Here is an example :
也许您可以查看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);
}
}
}
回答by Robert MacLean
My simple way of doing it to a string. Note the truesecond parameter on the StreamReaderconstructor. This tells it to detect the encoding from the byte order marks and may help with the encoding issue you are getting as well.
我对字符串执行此操作的简单方法。注意构造函数的true第二个参数StreamReader。这告诉它从字节顺序标记中检测编码,并可能有助于解决您遇到的编码问题。
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();
}
回答by Stew-au
In powershell, I have this function:
在powershell中,我有这个功能:
function GetWebPage
{param ($Url, $Outfile)
$request = [System.Net.HttpWebRequest]::Create($SearchBoxBuilderURL)
$request.AuthenticationLevel = "None"
$request.TimeOut = 600000 #10 mins
$response = $request.GetResponse() #Appending "|Out-Host" anulls the variable
Write-Host "Response Status Code: "$response.StatusCode
Write-Host "Response Status Description: "$response.StatusDescription
$requestStream = $response.GetResponseStream()
$readStream = new-object System.IO.StreamReader $requestStream
new-variable db | Out-Host
$db = $readStream.ReadToEnd()
$readStream.Close()
$response.Close()
#Create a new file and write the web output to a file
$sw = new-object system.IO.StreamWriter($Outfile)
$sw.writeline($db) | Out-Host
$sw.close() | Out-Host
}
And I call it like this:
我这样称呼它:
$SearchBoxBuilderURL = $SiteUrl + "nin_searchbox/DailySearchBoxBuilder.asp"
$SearchBoxBuilderOutput="D:\ecom\tmp\ss2.txt"
GetWebPage $SearchBoxBuilderURL $SearchBoxBuilderOutput
回答by Stew-au
You forgot to define "buffer" and "totalBytesRead":
你忘了定义“buffer”和“totalBytesRead”:
using ( FileStream localFileStream = ....
{
byte[] buffer = new byte[ 255 ];
int bytesRead;
double totalBytesRead = 0;
while ((bytesRead = ....
回答by Jo?o Paulo Melo
I faced a similar situation:
我遇到过类似的情况:
I was trying to read raw response in case of an HTTP error consuming a SOAP service, using BasicHTTPBinding.
我试图在使用 BasicHTTPBinding 的 HTTP 错误使用 SOAP 服务的情况下读取原始响应。
However, when reading the response using GetResponseStream(), got the error:
但是,在使用 读取响应时GetResponseStream(),出现错误:
Stream not readable
流不可读
So, this code worked for me:
所以,这段代码对我有用:
try
{
response = basicHTTPBindingClient.CallOperation(request);
}
catch (ProtocolException exception)
{
var webException = exception.InnerException as WebException;
var alreadyClosedStream = webException.Response.GetResponseStream() as MemoryStream;
using (var brandNewStream = new MemoryStream(alreadyClosedStream.ToArray()))
using (var reader = new StreamReader(brandNewStream))
rawResponse = reader.ReadToEnd();
}

