File tree 1 file changed +45
-0
lines changed 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ ------
2
+ Async Http Client - Zero Bytes Copy
3
+ ------
4
+ Jeanfrancois Arcand
5
+ ------
6
+ 2012
7
+
8
+ Zero Bytes Copy
9
+
10
+ When uploading or downloading bytes, it is important to try to avoid buffering bytes in memory.
11
+
12
+ * Upload
13
+
14
+ On the upload side, the mechanism is enabled by default when setting the <<<Request>>>'s body to a File:
15
+
16
+ +-----+
17
+ AsyncHttpClient client = new AsyncHttpClient();
18
+ File file = new File("file.avi");
19
+ Future f = client.preparePut("http://localhost").setBody(file).execute();
20
+ +-----+
21
+
22
+ If you can't use a File, the recommended way is to use a <<<BodyGenerator>>>. It is strongly recommended to avoid
23
+ using <<<InputStream>>> as the library will unfortunately buffer the entire content in memory in order to set the
24
+ <<<content-lenght>>>, which can cause out of memory error.
25
+
26
+ * Download
27
+
28
+ On the download side, you can use the <<<HttpResponseBodyPart.writeTo>>> to avoid loading bytes in memory and
29
+ unnecessary copy:
30
+
31
+ +-----+
32
+ AsyncHttpClient client = new AsyncHttpClient();
33
+ File tmp = new File("zeroCopy.txt");
34
+ final FileOutputStream stream = new FileOutputStream(tmp);
35
+ Future f = client.prepareGet("http://localhost/largefile.avi").execute(new AsyncHandler() {
36
+ public void onThrowable(Throwable t) { }
37
+
38
+ public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
39
+ bodyPart.writeTo(stream);
40
+ return STATE.CONTINUE;
41
+ }
42
+
43
+ { .... } });
44
+ Response resp = f.get();
45
+ +-----+
You can’t perform that action at this time.
0 commit comments