Question

How to implement http streaming client on android?

I have a comet streaming server - which gets an http request, keep it open and flush data once in a while.

How can I make a http post request from Android and keep handling the flushes which the server sent me (with the current open connection)? Notice that the response headers contains : Transfer-Encoding:chunked

I've tried to work with the HttpClient and HttpPost and ChunkedInputStream but couldn't handled this in the right way - is there a way to handle this in an callback base way, I mean to get some event on each flush and then to handle the current content?

Edited: Currently there are two solutions which I've thought of :

1) Read byte by byte and search for an end delimiter, once I got the end delimiter I can process the last message and continue to block the reading thread on the read action - until the next message arrives.

2) Send the length of the message and after that the message itself (from the server), then on my android app I'll try to get the last message by reading x bytes (according to the first length msg) and after that let the reading thread to block on the read action untill the next message arrives.

Was it helpful?

Solution

So the solution is:

Use standard http client like DefaultHttpClient or AndroidHttpClient and while processing the request just use the "read" function of the Reader. For example:

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
char[] msgsReadArray = new char[streamingArrayMaxCapacity];
int currentCharsCount = 0;
int currOffset = 0;
int currMsgBytesLength = 0;
while ((currentCharsCount = reader.read(msgsReadArray, currOffset , streamingArrayMaxCapacity - currOffset)) != -1 ) {
     String lastStreamingMsg = new String(msgsReadArray, 0, currMsgBytesLength);
     currOffset += currentCharsCount;
}

When the connection will be closed you'll get "-1" as the result of the read. Of course you'll have to handle exceptions and problematic situations - and also you might want to decide on a protocol for sending the streaming msgs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top