2

I'm trying to establish a persistent HTTP connection to an API endpoint that publishes chunked JSON responses as new events occur. I would like to provide a callback that is called each time the server sends a new chunk of data, and keep the connection open indefinitely. As far as I can tell, neither HttpClient nor HttpUrlConnection provide this functionality.

Is there a way to accomplish this without using a TCP socket?

allenc
  • 59
  • 5

2 Answers2

0

One solution would be to use a delimeter such as \n\n to separate each json event. You could remove blank lines from original json before sending. Calling setChunkedStreamingMode(0) allows you to read content as it comes in (rather than after the entire request has been buffered). Then you can simply go through each line, storing them, until a blank line is reached, then parse the stored lines as JSON.

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setChunkedStreamingMode(0);
conn.connect();

InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sBuffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
    if (line.length() == 0) {
        processJsonEvent(sBuffer.toString());
        sBuffer.delete(0, sBuffer.length());
    } else {
        sBuffer.append(line);
        sBuffer.append("\n");
    }
}
snydergd
  • 503
  • 7
  • 11
-1

As far as I can tell, Android's HttpURLConnection doesn't support receiving chunks of data across a persistent HTTP connection; it instead waits for the response to fully complete.

Using HttpClient, however, works:

HttpClient httpClient = new DefaultHttpClient();

try {
    HttpUriRequest request = new HttpGet(new URI("https://www.yourStreamingUrlHere.com"));
} catch (URISyntaxException e) {
    e.printStackTrace();
}

try {
    HttpResponse response = httpClient.execute(request);
    InputStream responseStream = response.getEntity().getContent();
    BufferedReader rd = new BufferedReader(new InputStreamReader(responseStream));

    String line;
    do {
        line = rd.readLine();
        // handle new line of data here
    } while (!line.isEmpty());


    // reaching here means the server closed the connection
} catch (Exception e) {
    // connection attempt failed or connection timed out
}
allenc
  • 59
  • 5
  • unfortunately ```HttpClient``` is deprecated in favor of ```HttpURLConnection``` (and it has been removed in Android 6). – bj0 Oct 27 '15 at 00:51
  • i think youre wrong about HttpURLConnetction, it can receive chunk data by using a SAX Handler – Rashid Jun 28 '16 at 03:28