I'm implementing a program in Java that downloads web pages using the HTTP protocol. After sending a GET
request to a server and reading the response headers (incl. the content-length
) the program reads into a char
array the amount of chars (as specified in the content-length
).
I've tried using both BufferedReader
and InputStreamReader
classes.
If the content-length
is high enough, only part of the stream is read and the rest of the bytes are not touched (like my end has read all available bytes and the other end hadn't finished writing).
As stated in the documentation of the BufferedReader
class:
This iterated
read
continues until one of the following conditions becomes true: *The specified number of characters have been read The read
method of the underlying stream returns *-1
, indicating end-of-file, or * *The ready
method of the underlying stream * returnsfalse
, indicating that further input requests * would block.
I'm afraid bullet number 3 is causing the read
to quit in the middle although the amount of bytes specified not yet read.
I can implement this functionality myself, but I was wondering if there's any class that ignores bullet number 3 and blocks until all bytes have been read, I could not find one.
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(stream))) {
char[] arr = new char[contentLength];
buffer.read(arr, 0, contentLength);
text.append(arr);
}
The meaning of the part about the ready()
method of the underlying Reader
is that it will block until at least one character has been transferred, but not block again. There is no guarantee it will fill the buffer.
You have to loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.