关于http请求卡死的处理

大家在做http请求时可能会遇到这种情况,明明设置了connetTimeOut和SocketTimeOut可是在实际使用的过程中却还是无法在设置的时间内得到响应结果(正确的或者异常的),请求就一直处于卡死状态,这种情况在手机端会比较常见(特别是网络环境不佳的时候),具体原因暂时不知,但我们可以对这种情况做下处理,这样不至于导致app处于一直等待的卡死状态。使用FutureTask对请求做定时处理,在限定时间内返回返回结果,不管http请求是否完成。一般我们可以把FutureTask的时间限定的长一些,一般足以让http请求正常返回就行。下面上代码

public static HttpResult proc(HttpClient client, HttpUriRequest req, Charset charset, int count) throws Exception
	{
		ExecutorService executor = Executors.newSingleThreadExecutor();
        FutureTask<HttpResponse> futureTask = new FutureTask<HttpResponse>(
				new Callable<HttpResponse>() {// 使用Callable接口作为构造参数
					public HttpResponse call() {
						HttpResponse response = null;
						try {
							response = client.execute(req);
						} catch (Exception e) {
						}
						return response;
					}
				});
		executor.execute(futureTask);
        
		HttpResponse response = null;
		try {
			// 这里是限定2分钟内
			response = futureTask.get(120000, TimeUnit.MILLISECONDS);
		} catch (TimeoutException e) {
			futureTask.cancel(true);
		} finally {
			executor.shutdown();
		}
		if(response == null) {
			return new HttpResult(response, req);
		}
		if (response.getStatusLine().getStatusCode() == 302 || response.getStatusLine().getStatusCode() == 301)
		{
			Header header = response.getFirstHeader("Location");
			if (header != null)
			{
				String location = header.getValue();
				System.out.println("location:" + location);
				HttpGet get = new HttpGet(location);
				return proc(client, get, StandardCharsets.UTF_8, count);
			}
			return new HttpResult(response, req, charset);
		}
		HttpResult rh = new HttpResult(response, req, charset);
		return rh;
	}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值