【发布时间】:2014-05-10 13:38:23
【问题描述】:
我需要向同一个 URL 发出多个 GET 请求,但查询不同。我将在移动设备 (Android) 上执行此操作,因此我需要尽可能优化。我从观看 Google 的 Android 网络研讨会中了解到,连接到服务器大约需要 200 毫秒,而且进行数据呼叫还涉及各种其他延迟。我只是想知道是否有一种方法可以优化向同一个 URL 发出多个请求的过程以避免其中一些延迟?
到目前为止,我一直在使用以下方法,但我已经调用了 6 次,每个 GET 请求调用一次。
//Make a GET request to url with headers.
//The function returns the contents of the retrieved file
public String getRequest(String url, String query, Map<String, List<String>> headers) throws IOException{
String getUrl = url + "?" + query;
BufferedInputStream bis = null;
try {
connection = new URL(url + "?" + query).openConnection();
for(Map.Entry<String, List<String>> h : headers.entrySet()){
for(String s : h.getValue()){
connection.addRequestProperty(h.getKey(), s);
}
}
bis = new BufferedInputStream(connection.getInputStream());
StringBuilder builder = new StringBuilder();
int byteRead;
while ((byteRead = bis.read()) != -1)
builder.append((char) byteRead);
bis.close();
return builder.toString();
} catch (MalformedURLException e) {
throw e;
} catch (IOException e) {
throw e;
}
}
【问题讨论】: