I'm trying to save binary data recieved from remote server with code:
public static WebObjectResponse<byte[]> RequestBinary(string uri)
{
var streamData = GetResponseStream(uri);
if (streamData.StatusCode != 200)
{
return new WebObjectResponse<byte[]> {Result = new WebRequestResult(streamData.StatusCode)};
}
if (streamData.ContentLength == -1)
{
return new WebObjectResponse<byte[]> {Result = new WebRequestResult(204)}; // 204 = No Content
}
using (streamData.Stream)
{
var responseBuffer = new byte[streamData.ContentLength];
streamData.Stream.Read(responseBuffer, 0, responseBuffer.Length);
return new WebObjectResponse<byte[]>
{
Data = responseBuffer,
Result = WebRequestResult.CreateSuccessfull()
};
}
}
private static WebStreamResponse GetResponseStream(string uri)
{
try
{
var response = CreateRequest(uri).GetResponse();
return new WebStreamResponse
{
StatusCode = 200,
Stream = response.GetResponseStream(),
ContentLength = response.ContentLength
};
}
catch (WebException e)
{
return new WebStreamResponse {StatusCode = (int) ((HttpWebResponse) e.Response).StatusCode};
}
catch (Exception e)
{
throw;
}
}
response.ContentLength has value -1, but Fiddler shows me another picture:
That's why i had to add a double check (response.ContentLength != -1) to prevent exception throwing.
How I have to change C# code to recieve a valid response stream?
Aucun commentaire:
Enregistrer un commentaire