Android - 如何打开接收分块响应的持久HTTP连接?

时间:2014-08-20 01:47:38

标签: android http chunked

我尝试建立与API端点的持久HTTP连接,该端点在新事件发生时发布分块JSON响应。我想提供一个每次服务器发送新数据块时调用的回调,并保持连接无限期打开。据我所知,HttpClientHttpUrlConnection都没有提供此功能。

有没有办法在不使用TCP套接字的情况下完成此任务?

2 个答案:

答案 0 :(得分:0)

一种解决方案是使用\n\n之类的分隔符来分隔每个json事件。您可以在发送之前从原始json中删除空白行。调用setChunkedStreamingMode(0)允许您在内容读取时(而不是在整个请求被缓冲后)。然后你可以简单地遍历每一行,存储它们,直到到达一个空行,然后将存储的行解析为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");
    }
}

答案 1 :(得分:-1)

据我所知,Android HttpURLConnection并不支持通过持久HTTP连接接收数据块;它反而等待响应完全完成。

然而,使用HttpClient可以起作用:

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
}