0

I have a Android Client Code (Here i am checking the timeout for internetconnection-doInBackground) (partly based on this answer by kuester2000):

public static void isNetworkAvailable(Context context){
    HttpGet httpGet = new HttpGet("http://www.google.com");
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    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 = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    try{
        Log.d(TAG, "Checking network connection...");
        httpClient.execute(httpGet);
        Log.d(TAG, "Connection OK");
        return;
    }
    catch(ClientProtocolException e){
        e.printStackTrace();
    }
    catch(IOException e){
        e.printStackTrace();
    }

    Log.d(TAG, "Connection unavailable");
}

My Question:: How to check Timeout for my Apache Client below


My Apache Code (doInBackground)::

protected Void doInBackground(String... urls) {
        JSONObject jsonObject;  
        JSONArray jsonArrayTable;
        final HttpClient Client = new DefaultHttpClient();
        try {
            publishProgress(1);
            publishProgress(2);
            getPlaceNameFromMapQuestApi();
            
            mDbHelper = new DatabaseHandler(context);
            db = mDbHelper.getWritableDatabase();//Start the Database Transaction
            db.beginTransaction();//Start the Database Transaction
            
            HttpGet httpget = new HttpGet(URL);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            Content = Client.execute(httpget, responseHandler);
            jsonObject = new JSONObject(Content);   
            //Get Data from from JSON ans perform Insertion
            parseTables(jsonObject);
            if(isDistanceCal==true) distanceCalculation();  
            db.setTransactionSuccessful();//Commit the Transaction
            isDownloadAsynTaskSucceed=true;//Set this flag so that i can start the next activity
        } catch (Exception e) {
            e.printStackTrace();
            if(isErr==false){
                errMsg=e.toString();
                isErr=true;
            }
            publishProgress(0);// This is necessary to make sure that alert is popped in opprogressupdate 
        }finally{
            db.endTransaction();//End the Database Transaction
            db.close();//close the database connection
        }
        return null;
    }
Ryan M
  • 18,333
  • 31
  • 67
  • 74
Devrath
  • 42,072
  • 54
  • 195
  • 297
  • how to check? or how to set? – Martin Konecny May 31 '14 at 04:31
  • What has doInBackground to do with your problem? You have some code to grab a google page which is indeed a very good method to check if you have internet connection. (You did not tell in which thread or asynctask you used it but ala not important). If there is no internet connection the request times out. Very clear. Now what is the question? – greenapps May 31 '14 at 06:54
  • @MartinKonecny ..... Its how to set :) ... Any Ideas ? – Devrath Jun 03 '14 at 08:41
  • @greenapps..... Yes if no internet connection, the connection times out but i want the connection to timeout occur say wait till 10 sec and then timeout .... in between try again and again for connectivity ...hope i am clear ! – Devrath Jun 03 '14 at 08:42

1 Answers1

0

You have to build Custom CustomHttpClient class for that

class CustomHttpClient {
    private static HttpClient customHttpClient;

    public static synchronized HttpClient getHttpClient() {
        if (customHttpClient != null) {
            return customHttpClient;
        }
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params,
                HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(params, true);
        HttpProtocolParams.setUserAgent(params,
                "Mozilla/5.0 (Linux; U; Android 2.2.1;");
        ConnManagerParams.setTimeout(params, 1000);
        HttpConnectionParams.setConnectionTimeout(params, 5000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        SchemeRegistry schReg = new SchemeRegistry();
        schReg.register(new Scheme("http", PlainSocketFactory
                .getSocketFactory(), 80));
        schReg.register(new Scheme("https",
                SSLSocketFactory.getSocketFactory(), 443));
        ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
                params, schReg);
        customHttpClient = new DefaultHttpClient(conMgr, params);
        return customHttpClient;
    }

    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }
}

public class Test extends Activity {
    private HttpClient httpClient;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        httpClient = CustomHttpClient.getHttpClient();
        getHttpContent();
    }

    public void getHttpContent() {
        try {
            HttpGet request = new HttpGet("http://www.google.com/");
            HttpParams params = request.getParams();
            HttpConnectionParams.setSoTimeout(params, 60000); // 1 minute
            request.setParams(params);
            Log.v("connection timeout", String.valueOf(HttpConnectionParams
                    .getConnectionTimeout(params)));
            Log.v("socket timeout",
                    String.valueOf(HttpConnectionParams.getSoTimeout(params)));

            String page = httpClient.execute(request,
                    new BasicResponseHandler());
            System.out.println(page);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

As a best practice I highly recommend to use Volley or Retrofit for as network libraries .

Source: java2s

LOG_TAG
  • 19,894
  • 12
  • 72
  • 105
  • What does the line HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Linux; U; Android 2.2.1;"); ....mean ? .... dows it mean this code is used for checking connectivity for Android 2.2.1 only or otherwise ? – Devrath Jun 09 '14 at 10:58
  • @CasperSky it's for server side validations , your rest api provider filter will check the user agent is valid or not ! – LOG_TAG Jun 09 '14 at 11:07
  • @CasperSky say good bye to this old buggy Apis , say hi to volley or retrofit for only focusing on what you needed and efficient optimized code! – LOG_TAG Jun 09 '14 at 11:08