2014-05-10 89 views
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; 
    } 
} 

回答

2

如果爲每一個請求,你期待着另一個結果是,你不能在同一請求中添加多個GET變量結合的請求,那麼你無法迴避的6次通話。

但是,您可以使用多個線程同時運行您的請求。您可以使用Java中的本機ExecutorService使用線程池方法。我會建議你使用ExecutorCompletionService來運行你的請求。由於處理時間不是CPU有限的,而是網絡有界的,所以您可以使用比當前CPU多的線程。

例如,在我的一些項目中,我使用10+,有時超過50個線程(在線程池中)同時檢索URL數據,即使我只有4個CPU核心。

+0

我有沒有辦法打開到服務器的連接,併爲每個請求使用相同的連接?所以我不必重新連接到服務器,然後每次斷開連接 – Edd

+0

請參閱此帖子的回覆:如果可以,HttpURLConnection將重新使用連接! http://stackoverflow.com/questions/5459162/tcp-connection-is-not-reused-for-http-requests-with-httpurlconnection –

相關問題