开发者

Why the need for InputStream in HTTP Clients? (Java)

I have been using various HTTP clients in java for getting various pieces of information from websites or for using web services (like the google maps geocoder)

The current cli开发者_C百科ent I'm working with is the HTTP Components client from Apache.

What I always wonder is why there is no .getText() or .getBytes() method that simply gives me all the contents of the url, but instead there are methods that return InputStream. What is the point or the reason for that?

It's not like I continuously comunicate with the server so that I would have to keep checking the stream. HTTP is stateless, so why is there no getText()/getBytes() method that simply returns the contents of the HTTP response (as String or byte[]), after it was received?


Because the server starts outputting the result in a stream, and the client gets it that way. You can buffer that stream in memory and transform it to a String / byte[], but you can also process parts of it, and discard them.


Because it's a network; because it's a stream; because the server response can be arbitrarily large. Same reasoning applies to files.


Besides what's already mentioned, an input stream is mandatory for the following scenario: the HTTP server providing a 1 GB response to a client running in a JVM with -Xmx512M. getBytes() or getString() can only result in an OutOfMemoryError, while reading the input stream (1K at a time) makes perfect sense.


You have EntityUtils.toString(entity).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜