1

I recently asked this question on SO: Grabbing JSON works from one link, not from another

I got an answer basically saying that getContentLength is optional by the server, so I would have to manually count the length myself. Well, it took me some time but I came up with some code that seems to get the right count, but I'm not sure if it's the "right" way to do it. Mostly because of my while(0==0) statement.

The exact answer I got was:

content-length is a header set by the responding server. It is optional, and google chooses not to send it for dynamically generated content (most servers don't). So you'll have to read the stream until you're out of bytes, rather than doing it in one go.

So this is my code that I came up with:

Reader reader = new InputStreamReader(inputStream);
int contentLength=0;
int cur;
while (0==0){
cur = reader.read();
if (cur == -1) {
break;
} else {
contentLength++;
}
}

Does that seem like a viable solution for counting the content length when the server doesn't provide you with one?

Community
  • 1
  • 1
EGHDK
  • 17,818
  • 45
  • 129
  • 204
  • Better replace while(0==0) with while(true) but why do you need the size at all. You can't really get the size without reading all the data. – MTilsted Aug 01 '13 at 01:22
  • If you read my other question, I'm simply just trying to get the JSON data, but the way I'm doing it now requires a length of content. Do you see a better way? – EGHDK Aug 01 '13 at 01:25
  • If you are using an existing JSon parser library, then that library most likely got a method which can parse Json directly from a stream. But if you try to write your own json parse(Why???) then have a look at http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string – MTilsted Aug 01 '13 at 02:11

1 Answers1

0

You can easily count the byte length of InputStream content sent by server in 2 lines:

ByteArrayInputStream bais = new ByteArrayInputStream(inputStream);
int length = bias.toByteArray().length;

Related to your approach:

int contentLength=0;
while (reader.read()>0){
contentLength++;
}

But what happens with the answer proposed in the question refered: int contentLength = connection.getContentLength();

That one is perfectly reasonable and viable.

Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148