I have a windows application that gets URL and download .jpeg
file. For some urls the ContentLength
property is -1, therefore it throws exception.
Here is my code:
var url = new Uri(sUrlToReadFileFrom[i]);
_request = (HttpWebRequest)WebRequest.Create(url);
var response = (System.Net.WebResponse)_request.GetResponse();
_response = response;
_response.Close();
and Here is the url: http://photos.autonexus.com/imager/115-005-CA/P2GTPI4AB9/640/10132013133959/1FAHP0HA3AR373228_1.jpg and here is some information about my http request:
Headers = {Transfer-Encoding: chunked
Connection: keep-alive
Content-Disposition: inline; filename="phpThumb_generated_thumbnail.jpeg"
Content-Type: image/jpeg
Date: Wed, 12 Nov 2014 00:31:29 GMT
Server: nginx
X-Powered-By: PleskLin}
I think the chunked header cause the problem but I have been googling for 2 days and there is no good solution or I cant find a good one.
Here is the screen shot of the error:
As you see in line 130, because _response.ContentLength is already -1 therefore iSize will be -1 and it throws exception at line 149.
There is no requirement that a site provide a Content-Length header, and there's no guarantee that it will be correct. So you can't depend on it. If you try to use the
ContentLength
property value to allocate an array, or for any purpose than information, you're going to have trouble. It simply isn't reliable in the general case.That's unfortunate, but you have to work around it. One solution is to create a
MemoryStream
. Then read blocks of data from the response stream and write them to the memory stream. Continue until the end of the response stream. Then get the `MemoryStream' buffer.Kind of a pain, but it's the best you can do if the
ContentLength
isn't reliable.For example: (Please note that I just tossed this off, so it might not be 100% working. But it should give you the idea.)