我使用HttpURLConnection訪問服務器上的某些PHP文件。我確實得到了正確的結果,但我的GET和響應之間的延遲非常長。我檢查出像stackoverflow網絡,並嘗試了幾個技巧,如System.setProperty(「http.keepAlive」,「假」); setRequestProperty(「連接」,「關閉」);但延遲仍然存在。然後,我植根了我的HTC,安裝了Shark,捕獲了服務器的流量,並將pcap文件複製到我的Wireshark。我比較了我的logCat和Wireshark,發現我顯式調用了HttpURLConnection.connect()和Android發送的第一個TCP SYN之間有20秒的差距。調用HttpURLConnection.connect()後啓動TCP SYN的長延遲
比較,我訪問服務器上的相同文件從Android瀏覽器,並花了< 2S ...
我的設備:HTC感覺(安卓2.3.4)
我的代碼(的AsyncTask)是這樣的:
System.setProperty("http.keepAlive", "false");
URL httpUrl = new URL(url);
HttpURLConnection connection = null;
connection = (HttpURLConnection) httpUrl.openConnection();
// prepare the request
if (connection != null) {
connection.setRequestProperty("connection", "close");
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setFollowRedirects(false);
connection.setRequestProperty("Accept-Encoding", "identity");
connection.setConnectTimeout(CONNECTION_TIMEOUT); // doesn't seem to work anyway
connection.setRequestProperty("User-Agent", USER_AGENT);
connection.connect();
// get response here .... getContentEncoding(); getContentLength(); getHeaderFieldKey(); etc
}
我已經在這個問題上已經工作了幾天,網絡仍然沒有線索周圍搜索。非常感謝您的任何評論。
您的網址如何顯示?你嘗試使用IP地址連接嗎?可能與DNS有關。 –
是的,我嘗試使用IP連接。 URL是這樣的:「http:// xxxx:port/folder1/index.php/Search-androidgroup?groupcode = 18240&pagesize = 40」 –
@Nikolay:我在connect()之前和之後放了logCat,發現connect ()方法調用需要20s才能完成。這是一種正常的行爲? –