2

新しいイベントが発生すると、チャンク化された JSON 応答を発行する API エンドポイントへの永続的な HTTP 接続を確立しようとしています。サーバーが新しいデータのチャンクを送信するたびに呼び出されるコールバックを提供し、接続を無期限に開いたままにしたいと思います。私が知る限り、この機能は提供されていHttpClientません。HttpUrlConnection

TCPソケットを使用せずにこれを達成する方法はありますか?

4

2 に答える 2

-1

私の知る限り、AndroidHttpURLConnectionは永続的な 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
}
于 2014-12-11T18:54:39.070 に答える