gpt4 book ai didi

android - 使用 HttpClient 的 HTTP 请求太慢?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:31:12 24 4
gpt4 key购买 nike

我正在尝试编写一个 android 应用程序,该应用程序将一些发布值发送到托管在专用服务器上的 php 文件并存储数组结果

代码是这样的

   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 秒

我在通过同一部手机和 3G 连接到互联网的计算机上运行了一个简单的 Ajax sendpost 脚本,执行相同的操作大约需要 0.300 毫秒,所以 ¿相同的连接,相同的操作,相差 2 秒?

///***更新

我在我的电脑上再次尝试了我的 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 参数, bool 值)

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 - 使用 HttpClient 的 HTTP 请求太慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12451687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com