laopifuq
laopifuq

Reputation: 27

set httpclient timeout in android

First it system.out "network found" ,and at the end I see no network.“code” doesn't come out public class NetUtil { public static boolean checkNet(Context context) {

    ConnectivityManager manager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = manager
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (info != null && info.isConnected()) {
        System.out.println("network found");
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(
                CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);
        httpclient.getParams().setParameter(
                CoreConnectionPNames.SO_TIMEOUT, 1000);

        HttpGet httpGet = new HttpGet("http://www.baidu.com");

        try {
            HttpResponse response = httpclient.execute(httpGet);

            int code = response.getStatusLine().getStatusCode();

            System.out.println("code:" + code);

            if (code == 200) {
                System.out.println("success");
                return true;
            } else if (code != 200) {
                System.out.println("failed");
                return false;
            }

        } catch (Exception e) {
            // TODO: handle exception
        }

    }

    System.out.println("no network");
    return false;

}

}

Upvotes: 0

Views: 1094

Answers (2)

Sazzad Hissain Khan
Sazzad Hissain Khan

Reputation: 40247

httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1500);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1500);

Upvotes: 1

Nadir Belhaj
Nadir Belhaj

Reputation: 12073

it is possible to set timeout for http requests this way

int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

Upvotes: 0

Related Questions