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.ByteArrayInputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.OutputStream;
34 import java.nio.charset.Charset;
35 import java.nio.charset.StandardCharsets;
36
37 import org.apache.hc.core5.annotation.Contract;
38 import org.apache.hc.core5.annotation.ThreadingBehavior;
39 import org.apache.hc.core5.http.ContentType;
40 import org.apache.hc.core5.util.Args;
41
42
43
44
45
46
47 @Contract(threading = ThreadingBehavior.IMMUTABLE)
48 public class StringEntity extends AbstractHttpEntity {
49
50 private final byte[] content;
51
52
53
54
55
56
57
58
59
60
61 public StringEntity(
62 final String string, final ContentType contentType, final String contentEncoding, final boolean chunked) {
63 super(contentType, contentEncoding, chunked);
64 Args.notNull(string, "Source string");
65 final Charset charset = ContentType.getCharset(contentType, StandardCharsets.UTF_8);
66 this.content = string.getBytes(charset);
67 }
68
69 public StringEntity(final String string, final ContentType contentType, final boolean chunked) {
70 this(string, contentType, null, chunked);
71 }
72
73 public StringEntity(final String string, final ContentType contentType) {
74 this(string, contentType, null, false);
75 }
76
77
78
79
80
81
82
83
84
85
86
87 public StringEntity(final String string, final Charset charset) {
88 this(string, ContentType.TEXT_PLAIN.withCharset(charset));
89 }
90
91 public StringEntity(final String string, final Charset charset, final boolean chunked) {
92 this(string, ContentType.TEXT_PLAIN.withCharset(charset), chunked);
93 }
94
95
96
97
98
99
100
101
102
103 public StringEntity(final String string) {
104 this(string, ContentType.DEFAULT_TEXT);
105 }
106
107 @Override
108 public final boolean isRepeatable() {
109 return true;
110 }
111
112 @Override
113 public final long getContentLength() {
114 return this.content.length;
115 }
116
117 @Override
118 public final InputStream getContent() throws IOException {
119 return new ByteArrayInputStream(this.content);
120 }
121
122 @Override
123 public final void writeTo(final OutputStream outStream) throws IOException {
124 Args.notNull(outStream, "Output stream");
125 outStream.write(this.content);
126 outStream.flush();
127 }
128
129 @Override
130 public final boolean isStreaming() {
131 return false;
132 }
133
134 @Override
135 public final void close() throws IOException {
136
137 }
138
139 }