通过FutureTask设置超时,用于请求网络,执行任何异步超时任务

24 篇文章 0 订阅
public class TestConnectTimeOut {

	private static final int STATE_COMPLETED_FAILED = 1;
	private static final int STATE_COMPLETED_SUCCESS = 2;
	private static final String[] REQUEST_URL = { "http://www.baidu.com",
			"http://www.qq.com", "http://www.iqiyi.com", "http://www.163.com",
			"http://www.taobao.com", "http://www.sina.com.cn" };

	private static ExecutorService mPool = Executors.newCachedThreadPool();

	public static void test() {
		mPool.execute(new Runnable() {
			public void run() {
				Log.e("connect", "connect  start !   ");
				test1();
				Log.e("connect", "connect  end !   ");
			}
		});
	}
	
	private static void test1() {
		for (int i = 0; i < REQUEST_URL.length; i++) {
			final int j = i;
			long time = System.currentTimeMillis();
			try {
				int a = executeTimedHttpMethod2(REQUEST_URL[j]);
				Log.e("connect", REQUEST_URL[j]
						+ "    connect  result !  -----   = " + a);

			} catch (ExecutionException e) {
				Log.e("connect", "connect  fail !  1111  ExecutionException   "
						+ REQUEST_URL[j]);
				e.printStackTrace();
			} catch (TimeoutException e) {
				Log.e("connect", "connect  fail !   2222   TimeoutException   "
						+ REQUEST_URL[j]);
				e.printStackTrace();
			} catch (InterruptedException e) {
				Log.e("connect",
						"connect  fail  !   333  InterruptedException   "
								+ REQUEST_URL[j]);
				e.printStackTrace();
			} finally {
				Log.e("connect", REQUEST_URL[j] + "   ---   take time  =  "
						+ (System.currentTimeMillis() - time));
			}
		}
	}

	private static <T> T execTimedCall(Callable<T> callable, Long timeout,
			TimeUnit unit) throws TimeoutException, ExecutionException,
			InterruptedException {
		FutureTask<T> task = new FutureTask<T>(callable);
		mPool.submit(task);
		return task.get(timeout, unit);
	}

	private static int executeTimedHttpMethod2(final String str)
			throws ExecutionException, TimeoutException, InterruptedException {
		int isSucc = execTimedCall(new Callable<Integer>() {
			@Override
			public Integer call() throws Exception {
				return connect2(str);
			}
		}, 3000l, TimeUnit.MILLISECONDS);
		return isSucc;
	}

	private static int connect2(String str) {
		DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient();
		try {

			HttpGet localObject2 = new HttpGet(str);
			HttpResponse response = localDefaultHttpClient
					.execute(localObject2);
			if (response.getStatusLine().getStatusCode() == 200) {
				return STATE_COMPLETED_SUCCESS;
			} else {
				return STATE_COMPLETED_FAILED;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return STATE_COMPLETED_FAILED;
		} finally {
			if (localDefaultHttpClient != null)
				localDefaultHttpClient.getConnectionManager().shutdown();
		}
	}

	private static HttpResponse executeTimedHttpMethod(final String str)
			throws ExecutionException, TimeoutException, InterruptedException {
		HttpResponse response = null;
		response = execTimedCall(new Callable<HttpResponse>() {
			@Override
			public HttpResponse call() throws Exception {
				return connect1(str);
			}
		}, 5000l, TimeUnit.MILLISECONDS);
		return response;
	}

	private static HttpResponse connect1(String str) {
		DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient();
		try {
			HttpGet localObject2 = new HttpGet(str);
			return localDefaultHttpClient.execute(localObject2);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (localDefaultHttpClient != null)
				localDefaultHttpClient.getConnectionManager().shutdown();
		}
		return null;
	}

	private static final void connect(String str) {
		DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient();
		long time = System.currentTimeMillis();
		try {

			HttpGet localObject2 = new HttpGet(str);
			localDefaultHttpClient.getParams().setParameter(
					"http.connection.timeout", 2000);
			localDefaultHttpClient.getParams().setParameter(
					"http.socket.timeout", 3000);

			HttpResponse response = localDefaultHttpClient
					.execute(localObject2);
			if (response.getStatusLine().getStatusCode() == 200) {
				Log.e("connect", "connect  success   !");
			} else {
				Log.e("connect", "connect  fail !");
			}
		} catch (Exception e) {
			Log.e("connect", "connect  fail !");
			e.printStackTrace();
		} finally {
			if (localDefaultHttpClient != null)
				localDefaultHttpClient.getConnectionManager().shutdown();

			Log.e("connect",
					str + "   ---   take time  =  "
							+ (System.currentTimeMillis() - time));
		}
	}

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值