提问者:小点点

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


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

有没有办法在不使用TCP套接字的情况下实现这一点?


共2个答案

匿名用户

一种解决方案是使用分隔符,例如\n\n来分隔每个json事件。您可以在发送之前从原始json中删除空行。调用setChankedStreamingMode(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");
    }
}

匿名用户

据我所知,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
}