Make execute() of HttpDefaultClient very slow

2019-03-22 04:44发布

问题:

I have massive performance problems with the execute method of the execute() method of the HttpDefaultClient.

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.

Is use this 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;

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

Creating the client like this:

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

Using: HTC Wildfire, Android 2.2.1

回答1:

codes above works fine.

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

for first time to post data to server and got response , it cost me 10--20 seconds.

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 .