2
对于我的应用程序,我需要从本地网络上的服务器上托管的网页获取最新数据。Android:快速Web请求
因此,我要求最新的页面与HTTP GET
,当收到数据时,我发送另一个请求。
在我目前的实现中,每个请求的响应时间为100 - 120毫秒。有没有可能使这更快,因为它是相同的网址,请求。
例如,保持连接在页面上打开并在不设置新连接的情况下刷新最新数据?
此页面大约900-1100字节。
HTTP GET代码:
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;
}
阅读的InputStream
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();
}