其他分享
首页 > 其他分享> > android – 使用HttpClient的HTTP请求太慢了?

android – 使用HttpClient的HTTP请求太慢了?

作者:互联网

我正在尝试编写一个Android应用程序,它将一些帖子值发送到托管在专用服务器上的php文件并存储数组resoult

代码是这样的

   HttpPost httppost;
    DefaultHttpClient httpclient;

    httppost = new HttpPost("http://IP/script.php"); 
    HttpParams param = new BasicHttpParams(); 
    param.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);


  //  httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    HttpProtocolParams.setContentCharset(param, "UTF-8");

    httpclient = new DefaultHttpClient(param);

    ResponseHandler <String> res=new BasicResponseHandler(); 
    List<NameValuePair> nameValuePairs;

    nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("id","1"));
    nameValuePairs.add(new BasicNameValuePair("api", "1"));


    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
Log.v("1",System.currentTimeMillis()+"");// Log to know the time diff
    String result= httpclient.execute(httppost, res);
Log.v("2",System.currentTimeMillis()+""); //  Log to know the time diff

这段代码浪费了大约2.5秒(在3G或WiFi上)发送帖子并从服务器获得“ok”字符串,即使有好的wifi这次只下来2.2 / 2.0秒

我在我的计算机上运行了一个简单的Ajax发送邮件脚本,通过同一部手机和3G连接到互联网,需要大约.300ms才能做同样的事情¿相同的连接,相同的动作,2秒的差异?

/// *** UPDATE

我在我的计算机上再次尝试了我的jquery脚本(带有移动3G / HDSPA连接)

平均时间响应约为250毫秒,但总是第一次请求高达1.7秒,我试图发送间隔为30秒的帖子,我得到平均1.5秒的时间,然后我试图发送间隔为2秒的帖子,第一次是1.41s,接近252ms

在这里,你们可以查看图表:http://i46.tinypic.com/27zjl8n.jpg

这种与电缆连接(标准家庭DSL)相同的测试始终提供约170ms间隔的固定时间响应(这里没有可靠的参数,但恕我直言,可能第一次尝试略高一点)

因此,在第一次尝试中有一些(或错误的)严重影响移动连接的东西,任何想法的人?

解决方法:

尝试使用此配置

HttpClient httpclient = new DefaultHttpClient();
HttpParams httpParameters = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, WAIT_RESPONSE_TIMEOUT);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);

这是关于setTcpNoDelay的javadoc:

public static void setTcpNoDelay(HttpParams params,boolean value)

Since: API Level 1

Determines whether Nagle’s algorithm is to be used. The Nagle’s
algorithm tries to conserve bandwidth by minimizing the number of
segments that are sent. When applications wish to decrease network
latency and increase performance, they can disable Nagle’s algorithm
(that is enable TCP_NODELAY). Data will be sent earlier, at the cost
of an increase in bandwidth consumption.

Parameters

value true if the Nagle’s algorithm is to NOT be used (that is enable
TCP_NODELAY), false otherwise.

标签:android,eclipse,httpclient,keep-alive,asynchttpclient
来源: https://codeday.me/bug/20190613/1231820.html