对于我的应用程序,我需要从本地网络上的服务器上托管的网页获取最新数据。
所以我用 a 请求最新的页面,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();
}