私のアプリケーションでは、ローカルネットワーク上のサーバーでホストされているWebページから最新のデータを取得する必要があります。
そこで、で最新のページをリクエストしHTTP GET
、データを受信したら別のリクエストを送信します。
現在の実装では、リクエストごとに約100〜120ミリ秒に達します。要求されたのと同じURLなので、これをより速くする可能性はありますか?
たとえば、接続をページに開いたままにして、新しい接続を設定せずに最新のデータをgrepしますか?
このページは約900〜1100バイトです。
HTTP取得コード:
public static String makeHttpGetRequest(String stringUrl) {
try {
URL url = new URL(stringUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(300);
con.setConnectTimeout(300);
con.setDoOutput(false);
con.setDoInput(true);
con.setChunkedStreamingMode(0);
con.setRequestMethod("GET");
return readStream(con.getInputStream());
} catch (IOException e) {
Log.e(TAG, "IOException when setting up connection: " + e.getMessage());
}
return null;
}
入力ストリームの読み取り
private static String readStream(InputStream in) {
BufferedReader reader = null;
StringBuilder total = new StringBuilder();
try {
String line = "";
reader = new BufferedReader(new InputStreamReader(in));
while ((line = reader.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, "IOException when reading InputStream: " + e.getMessage());
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return total.toString();
}