我的 HttpDefaultClient 的 execute() 方法的执行方法存在大量性能问题。
我目前正在使用它来将数据发布到服务器、接收 JSON 并反序列化数据。我的手机打电话需要 8 到 30 秒。如果我切换到 Wifi(速度相当快,在我的 PC 上同样的通话需要 300 毫秒),则需要 3 秒到 8 秒。至少 90% 的时间花在执行方法上。
是使用这段代码:
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)有没有更快的方法?
像这样创建客户端:
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 Wildfire,Android 2.2.1