Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Trick to apply Http connection timeout for post and get method in android?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 539
    Comment on it

    While working with application that connects to a web service and sometime it wait too long if it can't get a connection. To avoid this too long waiting you can set connection timeout timing of the HTTP params as per you want.

    If you want to do so you just have to apply this simple trick given below in you code :-

    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
    HttpConnectionParams.setConnectionTimeout(client.getParams(),15000); 
    

    LIKE THIS:-

    public static String checkLogin(String url,ArrayList<NameValuePair> params)
    {
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
        HttpConnectionParams.setConnectionTimeout(client.getParams(),15000);
    
        //final DefaultHttpClient client = new DefaultHttpClient();
        HttpPost method=null;
        try {
            method = new HttpPost(new URI(url));
            method.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
    
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) 
        {
            e.printStackTrace();
        }
        HttpResponse res=null;
        try 
        {
            if(client!=null)
                res = client.execute(method);
    
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(res!=null)
        {
        try {
            String str = "";
            str = inputStreamToString(res.getEntity().getContent()).toString(); 
            return str;
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return "";
            } catch (IOException e) {
                e.printStackTrace();
                return "";
            }
        }
        else
        {
            return "";
        }
    }
    

    Best of Luck!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: