新しいイベントが発生すると、チャンク化された JSON 応答を発行する API エンドポイントへの永続的な HTTP 接続を確立しようとしています。サーバーが新しいデータのチャンクを送信するたびに呼び出されるコールバックを提供し、接続を無期限に開いたままにしたいと思います。私が知る限り、この機能は提供されていHttpClient
ません。HttpUrlConnection
TCPソケットを使用せずにこれを達成する方法はありますか?
私の知る限り、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
}