更新: 找到自己的答案,請參見下面:-)
嗨,使用HttpClient的HTTP Post請求需要2秒,爲什麼?
我'當前譯碼的Android應用程序,在使用HTTP POST和的AsyncTask後臺提交的東西。我爲此使用org.apache.http.client包。我根據我的代碼this example。
基本上,我的代碼看起來是這樣的:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.137:8880/form");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
Log.e(TAG,e.toString());
} catch (IOException e) {
Log.e(TAG,e.toString());
}
}
的問題是httpclient.execute(..)線大約需要1.5至3秒,我不明白爲什麼。使用HTTP Get請求一個頁面需要大約80毫秒左右,所以這個問題似乎並不是網絡延遲本身。
該問題似乎並未出現在服務器端,我也嘗試將數據發佈到http://www.disney.com/,結果相似。在本地向我的服務器發送數據時,Firebug顯示1毫秒的響應時間。
這發生在模擬器和我的Nexus One(都與Android 2.2)。
如果你想看完整的代碼,我已經把它放在GitHub。
這只是一個虛擬程序,通過按下按鈕在後臺使用AsyncTask執行HTTP Post。這是我的第一個Android應用程序,也是我第一個很長時間的Java代碼。並incidentially,也是我在Stackoverflow上的第一個問題;-)
httpclient.execute(httppost)需要這麼長時間的任何想法?
我遇到了這個完全相同的問題,除了更糟。它甚至可能需要20秒鐘才能完成一個'HttpPost'。我嘗試了你的修復,但它似乎沒有幫助。 – theblang 2014-03-13 22:00:56