Why is the Content-Length header omitted from server response when using HttpClient?

巧了我就是萌 提交于 2019-12-12 14:40:35

问题


I am using this question's source code How to asynchronous perform a httprequest and show the progress of downloading the response in order to fetch a webpage's html source and display a progressbar with the downloaded data so far and how much the total size of the page is.

That particular code doesn't actually work on ICS 4.0.3 because clHeaders[0] doesn't point to anything and an exception is raised called ArrayIndexOutOfBounds at index 0 because the Content-Length header is omitted from the server's response. I tried using getContentLength in case that was the problem - it returned a negative value of -1 then I iterated over all the headers and the Content-Length was not there. After removing those bits, the code works fine and a webpage is fetched, written to a file and the size as it is being downloaded is displayed but obviously not the end size till I actually download it all.

I only have three ideas of the cause:

  1. I am not sending a Content-Length header thus I am not receiving one either - but this sounds wrong. Plus I have no idea if the HttpClient isn't sending one in the background.
  2. I read here in another question that if the response of the server was streaming or chunked then getContentLength can return -1.
  3. Gzip? But I have no idea how to disable it or if it was enabled in the first place

If you are thinking it's the server that is broken, I tried many websites including Google and still no Content-Length header whatsoever.


回答1:


Content-Length header is optional, it's mostly only useful for HEAD request or for very large data where the client might decide they want to abort the request if the content is too large. So yes, Content-Length dies not always exist. Other than that, you should generally just get the content length by reading the data.




回答2:


There are cases where the Content-Length should not be included in the response or should be ignored. These cases are documented on the W3 site. If your content has a transfer encoding of gzip for example, the content-length should be ignored.



来源:https://stackoverflow.com/questions/14903404/why-is-the-content-length-header-omitted-from-server-response-when-using-httpcli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!