HTTP Post requests using HttpClient take 2 seconds, why?

后端 未结 2 1924
孤街浪徒
孤街浪徒 2020-12-04 10:15
Update: Found the answer myself, see below :-)

Hi,

I\'am currently coding an android app that submits stuff in the background usin

2条回答
  •  天涯浪人
    2020-12-04 10:48

    i am not on android, but i faced exactly the same kind of problem on windows platform with httpclient 4.0.1, after quite a bit of head scratching, i found the solution.

    HttpParams params = new BasicHttpParams();
    //this how tiny it might seems, is actually absoluty needed. otherwise http client lags for 2sec.
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpClient httpClient = new DefaultHttpClient(params);
    HttpResponse httpResponse;
    
    
    HttpPost httpPost = new HttpPost("http://"+server+":"+port+"/");
    StringEntity entity = new StringEntity(content, "utf-8");
    entity.setContentType("text/plain; charset=utf-8"); 
    httpPost.setEntity(entity);
    
    httpResponse=httpClient.execute(httpPost);
    
    String response = IOUtils.toString(httpResponse.getEntity().getContent(),encoding);
    httpResponse.getEntity().consumeContent();
    
    httpClient.getConnectionManager().shutdown();
    return(response);
    

    i have no idea why setting the parameters with HTTP1.1 version solves the problem. but it does. also even weirder, the symptom did not show if executing an HTTP Get request.

    anyhow, i hope this helps some out there !

    h

提交回复
热议问题