Http connection timeout on Android not working

前端 未结 5 1604
悲&欢浪女
悲&欢浪女 2020-11-27 12:29

I\'m writing an application that connects to a webservice and I don\'t want it to wait too long if it can\'t get a connection. I therefore set the connectionTimeout of the h

5条回答
  •  鱼传尺愫
    2020-11-27 12:53

    Try to do it this way:

    HttpPost httpPost = new HttpPost(url);
    StringEntity se = new StringEntity(envelope,HTTP.UTF_8);
    httpPost.setEntity(se);
    
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 3000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    BasicHttpResponse httpResponse = (BasicHttpResponse)  httpClient.execute(httpPost);
    
    HttpEntity entity = httpResponse.getEntity();
    return entity;
    

    You then can catch a possible ConnectTimeoutException.

提交回复
热议问题