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 Charset charset = contentType != null ? contentType.getCharset() : null;
66 if (charset == null) {
67 charset = StandardCharsets.ISO_8859_1;
68 }
69 this.content = string.getBytes(charset);
70 }
71
72 public StringEntity(final String string, final ContentType contentType, final boolean chunked) {
73 this(string, contentType, null, chunked);
74 }
75
76 public StringEntity(final String string, final ContentType contentType) {
77 this(string, contentType, null, false);
78 }
79
80
81
82
83
84
85
86
87
88
89
90 public StringEntity(final String string, final Charset charset) {
91 this(string, ContentType.TEXT_PLAIN.withCharset(charset));
92 }
93
94 public StringEntity(final String string, final Charset charset, final boolean chunked) {
95 this(string, ContentType.TEXT_PLAIN.withCharset(charset), chunked);
96 }
97
98
99
100
101
102
103
104
105
106 public StringEntity(final String string) {
107 this(string, ContentType.DEFAULT_TEXT);
108 }
109
110 @Override
111 public final boolean isRepeatable() {
112 return true;
113 }
114
115 @Override
116 public final long getContentLength() {
117 return this.content.length;
118 }
119
120 @Override
121 public final InputStream getContent() throws IOException {
122 return new ByteArrayInputStream(this.content);
123 }
124
125 @Override
126 public final void writeTo(final OutputStream outStream) throws IOException {
127 Args.notNull(outStream, "Output stream");
128 outStream.write(this.content);
129 outStream.flush();
130 }
131
132 @Override
133 public final boolean isStreaming() {
134 return false;
135 }
136
137 @Override
138 public final void close() throws IOException {
139
140 }
141
142 }