问题描述
我与HttpDefaultClient的execute()方法的执行方法,大量的性能问题。
I have massive performance problems with the execute method of the execute() method of the HttpDefaultClient.
我目前使用这种将数据发布到服务器,接收JSON和反序列化的数据。呼叫拿我的手机上787-8到30秒。如果我切换到无线(它的pretty快,相同的呼叫需要300ms的我的电脑)需要3秒8秒。至少90%的,时间是在执行方法花费。
I'm currently using this to post data to a Server, receiving JSON and deserialize the data. A call takes 8s to 30s on my phone. If I switch to Wifi (it's pretty fast, the same call takes 300ms on my PC) it takes 3s to 8s. At least 90% of that time is spend in the execute method.
时使用code:
HttpPost post = new HttpPost(DEST_URL);
HashMap<String, String> params = req.getPostParams();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (String key : params.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
post.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
HttpResponse response = httpClient.execute(post); // very slow!
return response;
我们还开发了iOS应用,它能够在1做同样的2秒。是否有针对http更快的方法(在未来HTTPS)?
We also develop an iOS app which is able to do the same within 1 to 2s. Is there a quicker way for http (https in the future)?
创建客户端是这样的:
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
final SSLSocketFactory socketFactory = SSLSocketFactory
.getSocketFactory();
socketFactory
.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", socketFactory, 443));
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
HttpClient client = new DefaultHttpClient(params);
应用:HTC野火的Android 2.2.1
Using: HTC Wildfire, Android 2.2.1
推荐答案
$ C $以上的CS正常工作。
codes above works fine.
如果我创建一个HttpClient的方式如下:
if i create an httpclient the following way:
DefaultHttpClient httpClient = new DefaultHttpClient();
// httpclient
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, mConnectionTimeOut);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
mSocketTimeOut);
首次发布数据到服务器并得到响应时,它花了我10--20秒。
for first time to post data to server and got response , it cost me 10--20 seconds.
但如果我创建一个HttpClient的按照上面的答案。
当第一次发布数据到服务器并得到响应,它的成本只有4秒钟,我认为它工作正常。
but if i create an HttpClient following the answer above. when first time to post data to server and got response , it cost just 4 seconds,and i think it works fine .
这篇关于让HttpDefaultClient很慢的execute()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!