2

私のアプリケーションでは、ローカルネットワーク上のサーバーでホストされている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();
}
4

1 に答える 1

0

私が知っているように、あなたが求めているような実装はありません。私はhttpリクエストをたくさん扱ってきましたが、あなたができる最善のことはコードです。注意が必要な別のことがあります...接続が遅い場合があり、その接続時間によっては、接続時間が長くなる場合もあれば、多くの場合、接続のタイムアウトが十分に大きくない場合もありますが、それはサーバーの問題です。

私の意見では、あなたは今持っているものを使うべきです。

于 2013-01-18T09:56:38.963 に答える