简单实现http下载超过指定时间,强制关闭连接

// 设置默认工厂类
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        loggerContext.getLogger("org.apache").setLevel(Level.valueOf("ERROR"));
        ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(8192).setFragmentSizeHint(8192).build();
        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultConnectionConfig(connectionConfig).build();
        OutputStream out = null;
        InputStream in = null;
        long start = System.currentTimeMillis();
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, new DefaultThreadFactory("timer", true));
        PriorityQueue<MutablePair<Long, HttpRequestBase>> queue = new PriorityQueue<>(1000, Comparator.comparing(pre -> pre.left));
        executorService.scheduleAtFixedRate(() -> {
            if (queue.isEmpty()) {
                return;
            }
            MutablePair<Long, HttpRequestBase> item = queue.peek();
            System.out.println(item.left + "-------" + System.currentTimeMillis());
            if (item.left < System.currentTimeMillis()) {
                System.out.println("========abort========");
                item.right.abort();
                queue.poll();
            }

        }, 0, 500, TimeUnit.MICROSECONDS);
        HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/test/12");
        long expireTime = System.currentTimeMillis() + 1000;
        MutablePair<Long, HttpRequestBase> getQueue = new MutablePair<>(expireTime, httpGet);
        queue.add(getQueue);
        try {
            RequestConfig config = RequestConfig.custom().setSocketTimeout(6000).build();
            httpGet.setConfig(config);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            in = entity.getContent();
            File file = new File("/Users/zengzh/test.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            out = new FileOutputStream(file);
            byte[] buffer = new byte[32];
            int readLength = 0;
            while ((readLength = in.read(buffer)) > 0) {
                byte[] bytes = new byte[readLength];
                System.arraycopy(buffer, 0, bytes, 0, readLength);
                out.write(bytes);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("cost time is " + (System.currentTimeMillis() - start));
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值