1

i am trying to create handler which will terminate the http request in case that the server is not responding over 20 seconds. and i would like to know what is the best approach to do that from the Async task class.

this is my code:

public class DBcontroller extends AsyncTask <List<NameValuePair>, Void, String>{

    private static String url = "";
    private  Context context = null ;
    public AsyncResponse delegate= null;

    private PropertyReader propertyReader;
    private Properties properties;

    public DBcontroller(Context mycontext,AsyncResponse myresponse) {
        context = mycontext;
        delegate = myresponse;
        propertyReader = new PropertyReader(context);
        properties = propertyReader.getMyProperties("config.properties");
        url = properties.getProperty("url");
    }



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        delegate.preProcess();



    }

    @Override
    protected String doInBackground(List<NameValuePair>... params) {
        return postDataToServer(params[0]);
    }

    @Override
    protected void onPostExecute(String resStr) {
        super.onPostExecute(resStr);
        delegate.handleResponse(resStr);

    }

    private String postDataToServer(List<NameValuePair> list) {
        //check
        for (int i=0;i<list.size();i++)
            Log.d("responseString", list.get(i).toString());
        //check
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        String responseString = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(list));
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity);
            Log.d("responseString1", responseString);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(responseString!= null)
             Log.d("responseString2", responseString);
        return responseString;
    }


}
Matan Tubul
  • 774
  • 3
  • 11
  • 33
  • 3
    I think this might help you http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java – Anton Shkurenko Dec 09 '15 at 13:36
  • http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html. HttpClient is deprecated use HttpUrlConnection or you can use okhttp where you can set time out. You can also get rid of some of the codes in for loop can keep them outside – Raghunandan Dec 09 '15 at 13:36

2 Answers2

1

http://developer.android.com/reference/java/net/HttpURLConnection.html

HttpUrlConnection has a setConnectionTimeout ( ) method which does just that.

HttpURLConnection http = (HttpURLConnection)     mURL.openConnection();
http.setConnectTimeout(15000); //timeout after 15 seconds
An SO User
  • 24,612
  • 35
  • 133
  • 221
1

Use:

httpUrlConnection.setConnectTimeout(5000); // 5s timeout
httpUrlConnection.setReadTimeout(5000); 

also you can post a handler which will call disconnect() on your Url connection:

    new Handler(Looper.getMainLooper()).postDelayed(new Runnable(){
      @Override
      public void run() {
        httpUrlConnection.disconnect();
      }
    }, 5000);

[edit]

HttpClient to Url conversion pseudocode - not tested!

  @TargetApi(Build.VERSION_CODES.GINGERBREAD)
  public boolean postToServer(String url, String postData, StringBuilder resultData) throws IOException {
    URL at_url = new URL(url);
    int responseCode = 0;
    try {
      HttpURLConnection httpUrlConnection = (HttpURLConnection) at_url.openConnection();

      httpUrlConnection.setUseCaches(false);
      httpUrlConnection.setRequestProperty("User-Agent", "MyAgent");
      httpUrlConnection.setConnectTimeout(30000);
      httpUrlConnection.setReadTimeout(30000);

      httpUrlConnection.setRequestMethod("POST");
      httpUrlConnection.setDoOutput(true);

      OutputStream os = httpUrlConnection.getOutputStream();
      try {
        os.write(postData.getBytes(Charset.forName("UTF-8")));
      } finally {
        os.flush();
        os.close();
      }

      httpUrlConnection.connect();

      String response = "";
      responseCode = httpUrlConnection.getResponseCode();
      if (responseCode == 200) {
        InputStream is = httpUrlConnection.getInputStream();
        response = convertStreamToString(is);
        // Read is to get results
      } else {
        InputStream is = httpUrlConnection.getErrorStream();
        response = convertStreamToString(is);
        // Read is to get error
      }
      resultData.append(response);

    }
    finally {
      // Cleanup
    }
    return responseCode == 200;
  }
marcinj
  • 48,511
  • 9
  • 79
  • 100