// 设置默认工厂类
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();
}
}
简单实现http下载超过指定时间,强制关闭连接
最新推荐文章于 2024-01-16 09:07:08 发布