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.client5.http.entity.mime;
29
30 import java.io.ByteArrayInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.InputStreamReader;
34 import java.io.OutputStream;
35 import java.io.Reader;
36 import java.nio.charset.Charset;
37 import java.nio.charset.StandardCharsets;
38
39 import org.apache.hc.core5.http.ContentType;
40 import org.apache.hc.core5.util.Args;
41
42
43
44
45
46
47
48
49 public class StringBody extends AbstractContentBody {
50
51 private final byte[] content;
52
53
54
55
56 public StringBody(final String text, final ContentType contentType) {
57 super(contentType);
58 Args.notNull(text, "Text");
59 final Charset charset = contentType.getCharset();
60 this.content = text.getBytes(charset != null ? charset : StandardCharsets.US_ASCII);
61 }
62
63 public Reader getReader() {
64 final Charset charset = getContentType().getCharset();
65 return new InputStreamReader(
66 new ByteArrayInputStream(this.content),
67 charset != null ? charset : StandardCharsets.US_ASCII);
68 }
69
70 @Override
71 public void writeTo(final OutputStream out) throws IOException {
72 Args.notNull(out, "Output stream");
73 final InputStream in = new ByteArrayInputStream(this.content);
74 final byte[] tmp = new byte[4096];
75 int l;
76 while ((l = in.read(tmp)) != -1) {
77 out.write(tmp, 0, l);
78 }
79 out.flush();
80 }
81
82 @Override
83 public long getContentLength() {
84 return this.content.length;
85 }
86
87 @Override
88 public String getFilename() {
89 return null;
90 }
91
92 }