.net http stream getresponsestream

.net - ¿Cuál es la mejor manera de leer GetResponseStream()?



http (6)

Olvidó definir "buffer" y "totalBytesRead":

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

¿Cuál es la mejor manera de leer una respuesta HTTP de GetResponseStream?

Actualmente estoy usando el siguiente enfoque.

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

No estoy seguro si esta es la forma más eficiente de leer una respuesta http.

Necesito la salida como cadena, he visto un artículo con un enfoque diferente, pero no sé si es bueno. Y en mis pruebas, ese código tenía algunos problemas de codificación en diferentes sitios web.

¿Cómo lees las respuestas web?


Tal vez podrías mirar la clase de WebClient . Aquí hay un ejemplo :

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


Mi forma simple de hacerlo con una cuerda. Tenga en cuenta el true segundo parámetro en el constructor StreamReader . Esto le indica que detecte la codificación de las marcas de orden de bytes y también puede ayudar con el problema de codificación que está recibiendo.

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


En PowerShell, tengo esta función:

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 }

Y lo llamo así:

$SearchBoxBuilderURL = $SiteUrl + "nin_searchbox/DailySearchBoxBuilder.asp" $SearchBoxBuilderOutput="D:/ecom/tmp/ss2.txt" GetWebPage $SearchBoxBuilderURL $SearchBoxBuilderOutput


Uso algo como esto para descargar un archivo desde una 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; }


Enfrenté una situación similar:

Intentaba leer la respuesta sin procesar en caso de que un error HTTP consumiera un servicio SOAP, utilizando BasicHTTPBinding.

Sin embargo, al leer la respuesta usando GetResponseStream() , obtuve el error:

Stream no legible

Entonces, este código funcionó para mí:

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