在android中设置httpclient超时

时间:2014-09-14 11:11:03

标签: java android httpclient

首先是system.out"网络找到" ,最后我看不到网络。“代码”没有出来        公共类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;

}

}

2 个答案:

答案 0 :(得分:0)

可以通过这种方式为http请求设置超时

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

答案 1 :(得分:0)

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