HTTP Post请求使用HttpClient需要2秒钟,为什么?

更新:自己find答案,见下面:-)

嗨,

我目前正在编写一个Android应用程序,使用HTTP Post和AsyncTask在后台提交内容。 我为此使用org.apache.http.client包。 我基于这个例子我的代码。

基本上,我的代码如下所示:

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毫秒左右,所以这个问题似乎并不是networking延迟本身。

这个问题似乎并没有出现在服务器端,我也曾尝试将数据发布到http://www.disney.com/ ,结果也相当缓慢。 在本地向我的服务器发送数据时,Firebug显示1毫秒的响应时间。

这发生在模拟器和我的Nexus One(都与Android 2.2)。

如果你想看完整的代码,我已经把它放在GitHub上 。

这只是一个虚拟程序,在后台使用AsyncTask按下button进行HTTP Post。 这是我的第一个Android应用程序,我的第一个Java代码很长一段时间。 另外,也是我在Stackoverflow上的第一个问题;-)

任何想法为什么httpclient.execute(httppost)需要这么久?

好吧,我自己解决了这个问题,还有一些调查。 我所要做的只是添加一个参数,将HTTP版本设置为1.1,如下所示:

 HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpClient httpclient = new DefaultHttpClient(params); 

我发现这要感谢非常好的HttpHelper类和书虫以及一些反复试验。

如果我没有记错,HTTP 1.0会为每个请求打开一个新的TCP连接。 这是否解释了大的延迟?

现在,HTTP POST请求需要在WLAN上花费50到150毫秒,而在3G上花费300到500毫秒。

我不是在Android上,但我面对与httpclient 4.0.1在Windows平台上完全相同的问题,经过相当多的头挠,我find了解决scheme。

 HttpParams params = new BasicHttpParams(); //this how tiny it might seems, is actually absoluty needed. otherwise http client lags for 2sec. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpClient httpClient = new DefaultHttpClient(params); HttpResponse httpResponse; HttpPost httpPost = new HttpPost("http://"+server+":"+port+"/"); StringEntity entity = new StringEntity(content, "utf-8"); entity.setContentType("text/plain; charset=utf-8"); httpPost.setEntity(entity); httpResponse=httpClient.execute(httpPost); String response = IOUtils.toString(httpResponse.getEntity().getContent(),encoding); httpResponse.getEntity().consumeContent(); httpClient.getConnectionManager().shutdown(); return(response); 

我不知道为什么用HTTP1.1版本设置参数解决了这个问题。 但它确实。 甚至更怪,症状没有显示,如果执行HTTP Get请求。

无论如何,我希望这有助于一些在那里!

H