0
我需要對同一個URL發出多個GET請求,但使用不同的查詢。我將在移動設備上執行此操作(Android),因此我需要儘可能優化。我通過觀看Google的Android網絡研討會了解到,連接到服務器需要大約200毫秒的時間,並且在進行數據呼叫時還存在各種其他延遲。我只是想知道是否可以優化向同一個URL發出多個請求以避免這些延遲的過程?高效地對Java中的同一網址發出多個GET請求
我一直在使用下面的方法到目前爲止,但我一直稱它爲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;
}
}
我有沒有辦法打開到服務器的連接,併爲每個請求使用相同的連接?所以我不必重新連接到服務器,然後每次斷開連接 – Edd
請參閱此帖子的回覆:如果可以,HttpURLConnection將重新使用連接! http://stackoverflow.com/questions/5459162/tcp-connection-is-not-reused-for-http-requests-with-httpurlconnection –