How to add timeout to an HTTP Post

6k Views Asked by At

Why the code is Not working for me, Even the connection is stale, (there is no response from the server for a long time, the code is not throwing any exception!

try{

    HttpParams httpParameters = new BasicHttpParams();  
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
    HttpConnectionParams.setSoTimeout(httpParameters, 3000);
    HttpClient client = new DefaultHttpClient(httpParameters);              
    HttpPost post = new HttpPost("url");  
    post.setParams(httpParameters);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("ab ", cd));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));           
    HttpResponse response = client.execute(post);           
    BufferedReader rd = new BufferedReader(new 

    InputStreamReader(response.getEntity().getContent()));              
    while ((line = rd.readLine()) != null) 
   {

   }
  }
   catch(java.net.SocketTimeoutException e4)
   {
      Toast.makeText(xyz.this, "Your connection is stale", 10000).show();
   }
   catch (IOException e2) 
   {
  Log.d("G22", "Entered Exception");    
   }
   catch (Exception e2) 
   {
      Toast.makeText(xyz.this, "Your connection is stale..", 10000).show();
      e2.printStackTrace();
      Log.d("G22", "Entered Exception");    
   }
2

There are 2 best solutions below

2
On BEST ANSWER

Do you have to use HttpClient and HttpPost? You could use an HttpURLConnection, which has the setConnectTimeout(int) method:

See my answer here for an example of using HttpsURLConnection for a POST operation.

0
On

U can Use this code

    HttpTransportSE MyandroidHttpTransport = new HttpTransportSE("http://www.webservicex.net/ConvertWeight.asmx",50000);
    //50000 is the timeout for this connection