を使用HttpUrlConnection
して、サーバーとの永続的な接続を確立し (Android はkeep-alive
デフォルトで使用)、受信したメッセージをストリームとして扱うことができます。
public class HttpRequest extends AsyncTask {
@Override
protected Object doInBackground(Object[] params){
try {
URL url = new URL("http://simpl.info/eventsource/index.php");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
Log.d("SSE", "http response: " + urlConnection.getResponseCode());
//Object inputStream = urlConnection.getContent();
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
Log.d("SSE reading stream", readStrem(inputStream)+"");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("SSE activity", "Error on url openConnection: "+e.getMessage());
e.printStackTrace();
}
return null;
}
}
private String readStrem(InputStream inputStream) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try{
reader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while((line = reader.readLine()) != null){
Log.d("ServerSentEvents", "SSE event: "+line);
}
}catch (IOException e){
e.printStackTrace();
}finally {
if(reader != null){
try{
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return response.toString();
}