AsyncHttpClient

Official repository and docs: https://github.com/AsyncHttpClient/async-http-client

Maven Dependency

Check the latest version of async-http-client at https://mvnrepository.com/artifact/org.asynchttpclient/async-http-client

<dependency>
<groupId>org.asynchttpclient</groupId>
<artifactId>async-http-client</artifactId>
<version>2.12.3</version>
</dependency>

Usage

Basic Usage

AsyncHttpClient provides 2 APIs for defining requests: bound and unbound. AsyncHttpClient and Dsl` provide methods for standard HTTP methods (POST, PUT, etc)

// bound, define request inline with execute()
Future<Response> whenResponse=asyncHttpClient.prepareGet("http://www.example.com/").execute(); // unbound, define request and execute separately
Request request=get("http://www.example.com/").build();
Future<Response> whenResponse=asyncHttpClient.executeRequest(request);

Client Configuration

Instead of default configuration, create a customized one with Dsl.config()

AsyncHttpClientConfig config = Dsl.config()
.setConnectTimeout(CONN_TIMEOUT)
.setRequestTimeout(REQ_TIMEOUT)
.setMaxRequestRetry(100)
.build();
AsyncHttpClient client = Dsl.asyncHttpClient(config);

Download To File

The default implementation accumulates the HTTP chunks received into an ArrayList. This could lead to high memory consumption, or an OutOfMemory exception when trying to download a large file. Use a FileChannel to write the bytes to our local file directly. We'll use the getBodyByteBuffer() method to access the body part content through a ByteBuffer.

// Open the file, enable append(not necessary in this example)
FileOutputStream os = new FileOutputStream(LOCAL_FILE, true);
// Create a default client
AsyncHttpClient client = Dsl.asyncHttpClient();
// Use Future to block till download complete, just for demostration
ListenableFuture<Response> whenResponse = client.prepareGet(FILE_URL).execute(new AsyncCompletionHandler<Response>() { @Override
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
os.getChannel().write(bodyPart.getBodyByteBuffer());
return State.CONTINUE;
} @Override
public Response onCompleted(Response response) throws Exception {
return response;
}
}); Response response=whenResponse.get();
// Thread will never exit if client is not closed
client.close();

You can get the bodyPart length and calculate the totoally received length

private int totalLength;

@Override
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
os.getChannel().write(bodyPart.getBodyByteBuffer());
receivedLength += bodyPart.length();
System.out.println(receivedLength);
if (bodyPart.isLast())
{
System.out.println("last");
return State.ABORT;
}
return State.CONTINUE;
}

Range Requests, Partial Download

You can modify the request header to download part of the file, as long as the server supports range request.

Response DefaultHttpResponse(decodeResult: success, version: HTTP/1.1)
HTTP/1.1 200 OK
Server: openresty
Date: Sun, 04 Dec 2022 13:35:21 GMT
Content-Type: application/octet-stream
Last-Modified: Thu, 21 Apr 2022 17:16:39 GMT
Connection: keep-alive
ETag: "62619177-1b58d5"
Accept-Ranges: bytes <--- this means the server supports range requests
content-length: 1792213

In Java code, create the request like

FileOutputStream os = new FileOutputStream(localFilePath, true);

Request request = Dsl.get(remoteUrl).setHeader(HttpHeaderNames.RANGE, "bytes="+offset+"-"+(offset + length - 1)).build();

ListenableFuture<FragmentResponse> whenResponse = client.executeRequest(request, new AsyncCompletionHandler<>() {
//...
});

You will get the response header as

Response DefaultHttpResponse(decodeResult: success, version: HTTP/1.1)
HTTP/1.1 206 Partial Content
Server: openresty
Date: Sun, 04 Dec 2022 13:27:14 GMT
Content-Type: application/octet-stream
Last-Modified: Fri, 15 Oct 2021 12:25:23 GMT
Connection: keep-alive
ETag: "61697333-268f48e"
X-RateLimit-Byte-Rate: 67108864
Content-Range: bytes 38797312-39845887/40432782
content-length: 1048576

Range Boundary

According to Hypertext Transfer Protocol (HTTP/1.1): Range Requests, the range boundaries are inclusive - inclusive. Examples of byte-ranges-specifier values:

  • The first 500 bytes (byte offsets 0-499, inclusive): bytes=0-499
  • The second 500 bytes (byte offsets 500-999, inclusive): bytes=500-999

Example Code Of Download Speed Limit

This is an example of controlling download speed by splitting file into fragments -- and download them piece by piece.

public class FragmentableDownloader {

    Logger log = LoggerFactory.getLogger(FragmentableDownloader.class);

    public static final int CONN_TIMEOUT = 60000;
public static final int REQ_TIMEOUT = 60000; private AsyncHttpClient client;
/**
* limit bytes per second
*/
private long rateLimit;
/**
* size of each fragment
*/
private long fragmentSize; private String remoteUrl; private String localFilePath; private long fileLength; private long timestamp; private long interval; public FragmentableDownloader(long rateLimit, long fragmentSize, String remoteUrl, String localFilePath) {
this.rateLimit = rateLimit;
this.fragmentSize = fragmentSize;
this.remoteUrl = remoteUrl;
this.localFilePath = localFilePath; AsyncHttpClientConfig config = Dsl.config()
.setConnectTimeout(CONN_TIMEOUT)
.setRequestTimeout(REQ_TIMEOUT)
.setMaxRequestRetry(100)
.build();
this.client = Dsl.asyncHttpClient(config); interval = fragmentSize / rateLimit;
} public FragmentResponse downloadFragment(long offset, long length) throws Exception { FileOutputStream os = new FileOutputStream(localFilePath, true); Request request = Dsl.get(remoteUrl).setHeader(HttpHeaderNames.RANGE, "bytes="+offset+"-"+(offset + length - 1)).build(); ListenableFuture<FragmentResponse> whenResponse = client.executeRequest(request, new AsyncCompletionHandler<>() {
private long totalLength;
private int byteTransferred = 0; @Override
public State onHeadersReceived(HttpHeaders headers) throws Exception {
String length = headers.get(HttpHeaderNames.CONTENT_RANGE);
int pos = length.lastIndexOf('/');
length = length.substring(pos + 1);
this.totalLength = Long.parseLong(length);
return State.CONTINUE;
} @Override
public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
os.getChannel().write(bodyPart.getBodyByteBuffer());
byteTransferred += bodyPart.length();
//log.info("byteTransferred: {}", byteTransferred);
return State.CONTINUE;
} @Override
public FragmentResponse onCompleted(Response response) throws Exception {
log.info("complete");
return new FragmentResponse(response.getStatusCode(), totalLength);
}
});
return whenResponse.get();
} public void download() throws Exception {
Files.deleteIfExists(Path.of(localFilePath));
long offset = 0;
FragmentResponse response = downloadFragment(0, fragmentSize);
offset += fragmentSize;
this.fileLength = response.getTotalLength();
if (this.fileLength <= fragmentSize) {
return;
}
while (offset < fileLength - 1) {
log.info("Offset: {}", offset);
timestamp = System.currentTimeMillis();
response = downloadFragment(offset, fragmentSize);
offset += fragmentSize;
long duration = System.currentTimeMillis() - timestamp;
log.info("file:{}, offset:{}, response: {}, speed:{}", fileLength, offset, response.getStatus(), fragmentSize / duration);
long wait = interval * 1000L - duration;
if (wait > 0) {
log.info("Sleep {} milliseconds for rate limit", wait);
Thread.sleep(wait);
}
}
log.info("Download finished");
client.close();
} public static void main(String[] args) throws Exception {
String url = "https://mirrors.ustc.edu.cn/ubuntu/dists/jammy/main/signed/linux-amd64/5.13.0-19.19/signed.tar.gz";
String path = "/home/milton/Downloads/signed.tar.gz";
long rateLimit = 500 * 1024L;
long fragmentSize = 10 * 1024 * 1024L;
FragmentableDownloader downloader = new FragmentableDownloader(rateLimit, fragmentSize, url, path);
downloader.download();
} public static class FragmentResponse {
private int status;
private long totalLength; public FragmentResponse(int status, long totalLength) {
this.status = status;
this.totalLength = totalLength;
} public int getStatus() {
return status;
} public long getTotalLength() {
return totalLength;
}
}
}

Ref

AsyncHttpClient And Download Speed Limit的更多相关文章

  1. Speed Limit 分类: POJ 2015-06-09 17:47 9人阅读 评论(0) 收藏

    Speed Limit Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 17967   Accepted: 12596 Des ...

  2. E - Speed Limit(2.1.1)

    E - Speed Limit(2.1.1) Time Limit:1000MS     Memory Limit:30000KB     64bit IO Format:%I64d & %I ...

  3. [ACM] poj 2017 Speed Limit

    Speed Limit Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 17030   Accepted: 11950 Des ...

  4. poj 2017 Speed Limit

    Speed Limit Time Limit: 1000MS   Memory Limit: 30000K Total Submissions: 17704   Accepted: 12435 Des ...

  5. zoj 2176 Speed Limit

    Speed Limit Time Limit: 2 Seconds      Memory Limit: 65536 KB Bill and Ted are taking a road trip. B ...

  6. POJ 2017 Speed Limit (直叙式的简单模拟 编程题目 动态属性很少,难度小)

                                                                                                      Sp ...

  7. Kattis - Speed Limit

    Speed Limit Bill and Ted are taking a road trip. But the odometer in their car is broken, so they do ...

  8. Poj 2017 Speed Limit(水题)

    一.Description Bill and Ted are taking a road trip. But the odometer in their car is broken, so they ...

  9. Speed Limit

    http://poj.org/problem?id=2017 #include<stdio.h> int main() { int n,mile,hour; ) { ,h = ; whil ...

  10. PyTorch DataLoader NumberWorkers Deep Learning Speed Limit Increase

    这意味着训练过程将按顺序在主流程中工作. 即:run.num_workers.   ,此外, ,因此,主进程不需要从磁盘读取数据:相反,这些数据已经在内存中准备好了. 这个例子中,我们看到了20%的加 ...

随机推荐

  1. 基于AHB_BUS的eFlash控制器设计-软硬件系统设计

    eFlash软硬件系统设计 软硬件划分 划分好软硬件之后,IP暴露给软件的寄存器和时序如何? 文档体系:详细介绍eflash控制器的设计文档 RTL代码编写:详细介绍eflash控制器的RTL代码 1 ...

  2. 如何使用Oracle Enterprise Manager Database Express连接到PDB数据库

    1.问题 1.1重复弹出登录框,无法登陆 关闭登录框,显示invalid container name 1.2 重启后PDB数据库处于mounted挂载状态,未打开导致使用 Enterprise 登陆 ...

  3. 2023-SWPU NSS秋季招新赛(校外赛道)Misc—我要成为原神高手WP

    1.题目信息 我是神里绫华的狗!!! 2.解题方法 有个genshin.h文件夹,打开看看发现里面是一堆文件夹0 1A 1A0等等,而且每个文件夹里面都有文件,0 1A 1A0...看着很眼熟,我们用 ...

  4. [转帖]CIDR

    什么是 CIDR? 无类别域间路由 (CIDR) 是一种 IP 地址分配方法,可提高互联网上的数据路由效率.每台连接到互联网的计算机.服务器和最终用户设备都有一个与之关联的唯一编号,称为 IP 地址. ...

  5. [转帖]Rust在windows下安装以后cargo build Error: linker `link.exe` not found

    D:\rust\runoob-greeting\greeting>cargo build error: linker `link.exe` not found | = note: 系统找不到指定 ...

  6. [转帖]PostgreSQL配置文件--WAL

    2022-12-23 3.1 Settings 3.1.1 fsync 字符串 默认: fsync = on 开启后强制把数据同步更新到磁盘,可以保证数据库将在OS或者硬件崩溃的后恢复到一个一致的状态 ...

  7. [转帖]深入理解mysql-第十章 mysql查询优化-Explain 详解(上)

    目录 一.初识Explain 二.执行计划-table属性 三.执行计划-id属性 四.执行计划-select_type属性 一条查询语句在经过MySQL查询优化器的各种基于成本和规则的优化会后生成一 ...

  8. [转帖]超能课堂(323) 为什么WiFi实际速率只有标称速率的一半?

    超能课堂(323) 为什么WiFi实际速率只有标称速率的一半? 开始的地方 协议速率与实际速率有何不同? 什么是"全双工"与"半双工"? 无线网络与有线网络的抗 ...

  9. [转帖]公钥基础设施(PKI,Public Key Infrastructure)闲谈

    https://zhuanlan.zhihu.com/p/384436119 背景 在现实空间中,人类的活动范围和接触人的范围有限,人和人最初的信任是建立在小团体或部落内部.随着全球化进展,人类的活动 ...

  10. [转帖]01-rsync备份方式

    https://developer.aliyun.com/article/885783?spm=a2c6h.24874632.expert-profile.284.7c46cfe9h5DxWK 简介: ...