This content has been marked as final. Show 10 replies
On the point of efficiency, a new String() is the same as a "" for your purposes.
A String is immutable so you += create a new appended string each time. Very inefficient for a large post.
DataInputStream is used to reading binary data and readLine is deprecated.
I suggest you use a class designed for using text.
new BufferedReader(new InputStreamReader(client.getInputStream()))
Then use a StringBuffer or StringBuilder to append each line.
Note: readLine strips newline characters. If you want to keep them I suggest you use readChars or append the newlines extra.
Better yet you could use the IOUtils class in the apache's commin IO library. With this you can do..
String text = IOUtils.toString(client.getInputStream());
Thnx for your response. But using BufferedReader or StringBuffer or readChars/readLine will(does) not solve my problem. After reading the http headers, when the stream encounters multiple '\r\n' reading fails. The while loop never terminates. I want a means to read the data that comes in after the HTTP headers.
The connection you receive is probably one of the kind: connection: keep-alive. Which means the stream will be kept open and you will not receive an eof marker. Thus the readline method will wait until input will become ready, which will never happen. You could solve this by checking if data is available for reading.
readLine() is deprecated, as a rule, always stay away from deprecated methods.
As for your problem, read the HTTP RFC first so you know what an HTTP response looks like. What you do is create a while loop that will read all data available until you reach the end of the header (the double CRLF or /r/n as you mention). At that point, parse the header you just read (convert them to strings, read the key/value pairs). Look for Content-Length if it exists. If it does, read data until total request bytes = Content-Length header field value. If no Content-Length is defined read until EOF. Depending on the Content-Type header field there will be either binary or textual data in the message body of the HTTP response. Again it's easier to read all X bytes of the message body (where X is the Content-Length or the number of bytes you can read without getting an EOF). Then throw that byte array into the appropriate parser depending on the content-type.
I still have the problem. After getting theYou shouldn't be in a while loop once you attempt to read the content itself. Once you have the content length and you are at the content itself all you do is read the number of bytes specified by the content length and then terminate.
content-length, i used the break command to quit the
while loop. But the statement read(content-length);
is still blocked.
You will find that you will also want to put a timeout on the read.