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 com.foxinmy.weixin4j.http.apache.content;
29
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33
34 import com.foxinmy.weixin4j.http.ContentType;
35 import com.foxinmy.weixin4j.http.apache.mime.MIME;
36
37
38
39
40
41
42
43
44 public class InputStreamBody extends AbstractContentBody {
45
46 private final InputStream in;
47 private final String filename;
48
49
50
51
52
53 public InputStreamBody(final InputStream in, final String mimeType,
54 final String filename) {
55 this(in, ContentType.create(mimeType), filename);
56 }
57
58 public InputStreamBody(final InputStream in, final String filename) {
59 this(in, ContentType.DEFAULT_BINARY, filename);
60 }
61
62
63
64
65 public InputStreamBody(final InputStream in, final ContentType contentType,
66 final String filename) {
67 super(contentType);
68 this.in = in;
69 this.filename = filename;
70 }
71
72
73
74
75 public InputStreamBody(final InputStream in, final ContentType contentType) {
76 this(in, contentType, null);
77 }
78
79 public InputStream getInputStream() {
80 return this.in;
81 }
82
83 @Override
84 public void writeTo(final OutputStream out) throws IOException {
85 try {
86 final byte[] tmp = new byte[4096];
87 int l;
88 while ((l = this.in.read(tmp)) != -1) {
89 out.write(tmp, 0, l);
90 }
91 out.flush();
92 } finally {
93 this.in.close();
94 }
95 }
96
97 @Override
98 public String getTransferEncoding() {
99 return MIME.ENC_BINARY;
100 }
101
102 @Override
103 public long getContentLength() {
104 try {
105 return in.available();
106 } catch (IOException e) {
107 return -1;
108 }
109 }
110
111 @Override
112 public String getFilename() {
113 return this.filename;
114 }
115
116 }