Search code examples
androidhttptimeoutandroid-internet

How to add timeout to an HTTP Post


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

Solution

  • 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.