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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3046424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:27:29  来源:igfitidea点击:

HTTP Post requests using HttpClient take 2 seconds, why?

androidhttphttpclient

提问by pableu

Update: Found the answer myself, see below :-)
更新:自己找到答案,见下文:-)

Hi,

你好,

I'am currently coding an android app that submits stuff in the background using HTTP Post and AsyncTask. I use the org.apache.http.clientPackage for this. I based my code on this example.

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

Basically, my code looks like this:

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

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());
    }
}

The problem is that the httpclient.execute(..) line takes around 1.5 to 3 seconds, and I do not understand why. Just requesting a page with HTTP Get takes around 80 ms or so, so the problem doesn't seem to be the network latency itself.

问题是httpclient.execute(..) 行大约需要 1.5 到 3 秒,我不明白为什么。仅使用 HTTP Get 请求页面大约需要 80 毫秒左右,因此问题似乎不是网络延迟本身。

The problem doesn't seem to be on the server side either, I have also tried POSTing data to http://www.disney.com/with similarly slow results. And Firebug shows 1 ms response time when POSTing data to my server locally.

问题似乎也不是在服务器端,我也尝试将数据发布到http://www.disney.com/,结果同样缓慢。Firebug 在本地将数据发布到我的服务器时显示 1 毫秒的响应时间。

This happens on the Emulator and with my Nexus One (both with Android 2.2).

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

If you want to look at the complete code, I've put it on GitHub.

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

It's just a dummy program to do HTTP Post in the background using AsyncTask on the push of a button. It's my first Android app, and my first java code for a long time. And incidentially, also my first question on Stackoverflow ;-)

这只是一个虚拟程序,只需按一下按钮即可使用 AsyncTask 在后台执行 HTTP Post。这是我的第一个 Android 应用程序,也是我很长时间以来的第一个 Java 代码。顺便说一句,也是我关于 Stackoverflow 的第一个问题 ;-)

Any ideas why httpclient.execute(httppost) takes so long?

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

回答by pableu

Allright, I solved this myself with some more investigation. All I had to do was to add a parameter that sets the HTTP Version to 1.1, as follows:

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

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

I found this thanks to the very nice HttpHelper Classfrom and-bookworm and some trial-and-error.

我发现这要感谢and- bookworm提供的非常好的HttpHelper 类以及一些反复试验。

If I remember correctly, HTTP 1.0 opens a new TCP connection for every request. Does that explain the large delay?

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

A HTTP POST request now takes between 50 and 150 ms over WLAN and something between 300 and 500 ms over 3G.

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

回答by henri

i am not on android, but i faced exactly the same kind of problem on windows platform with httpclient 4.0.1, after quite a bit of head scratching, i found the solution.

我不是在 android 上,但我在使用 httpclient 4.0.1 的 Windows 平台上遇到了完全相同的问题,经过一番摸索后,我找到了解决方案。

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);

i have no idea why setting the parameters with HTTP1.1 version solves the problem. but it does. also even weirder, the symptom did not show if executing an HTTP Get request.

我不知道为什么用 HTTP1.1 版本设置参数可以解决问题。但确实如此。更奇怪的是,如果执行 HTTP Get 请求,则症状没有显示。

anyhow, i hope this helps some out there !

无论如何,我希望这对那里的一些人有所帮助!

h

H