1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.hc.core5.http.io.entity;
29
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33
34 import org.apache.hc.core5.http.ContentType;
35 import org.apache.hc.core5.util.Args;
36
37
38
39
40
41
42 public class InputStreamEntity extends AbstractHttpEntity {
43
44 private final InputStream content;
45 private final long length;
46
47 public InputStreamEntity(
48 final InputStream inStream, final long length, final ContentType contentType, final String contentEncoding) {
49 super(contentType, contentEncoding);
50 this.content = Args.notNull(inStream, "Source input stream");
51 this.length = length;
52 }
53
54 public InputStreamEntity(final InputStream inStream, final long length, final ContentType contentType) {
55 this(inStream, length, contentType, null);
56 }
57
58 public InputStreamEntity(final InputStream inStream, final ContentType contentType) {
59 this(inStream, -1, contentType, null);
60 }
61
62 @Override
63 public final boolean isRepeatable() {
64 return false;
65 }
66
67
68
69
70 @Override
71 public final long getContentLength() {
72 return this.length;
73 }
74
75 @Override
76 public final InputStream getContent() throws IOException {
77 return this.content;
78 }
79
80
81
82
83
84
85
86
87 @Override
88 public final void writeTo(final OutputStream outStream) throws IOException {
89 Args.notNull(outStream, "Output stream");
90 try (final InputStream inStream = this.content) {
91 final byte[] buffer = new byte[OUTPUT_BUFFER_SIZE];
92 int readLen;
93 if (this.length < 0) {
94
95 while ((readLen = inStream.read(buffer)) != -1) {
96 outStream.write(buffer, 0, readLen);
97 }
98 } else {
99
100 long remaining = this.length;
101 while (remaining > 0) {
102 readLen = inStream.read(buffer, 0, (int) Math.min(OUTPUT_BUFFER_SIZE, remaining));
103 if (readLen == -1) {
104 break;
105 }
106 outStream.write(buffer, 0, readLen);
107 remaining -= readLen;
108 }
109 }
110 }
111 }
112
113 @Override
114 public final boolean isStreaming() {
115 return true;
116 }
117
118 @Override
119 public final void close() throws IOException {
120 content.close();
121 }
122
123 }