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