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.async.methods;
29
30 import java.nio.charset.Charset;
31 import java.nio.charset.StandardCharsets;
32
33 import org.apache.hc.core5.http.ContentType;
34 import org.apache.hc.core5.util.Args;
35
36
37
38
39
40
41 public final class SimpleBody {
42
43 private final byte[] bodyAsBytes;
44 private final String bodyAsText;
45 private final ContentType contentType;
46
47 SimpleBody(final byte[] bodyAsBytes, final String bodyAsText, final ContentType contentType) {
48 this.bodyAsBytes = bodyAsBytes;
49 this.bodyAsText = bodyAsText;
50 this.contentType = contentType;
51 }
52
53 static SimpleBody create(final String body, final ContentType contentType) {
54 Args.notNull(body, "Body");
55 if (body.length() > 2048) {
56 return new SimpleBody(null, body, contentType);
57 }
58 final Charset charset = (contentType != null ? contentType : ContentType.DEFAULT_TEXT).getCharset();
59 final byte[] bytes = body.getBytes(charset != null ? charset : StandardCharsets.US_ASCII);
60 return new SimpleBody(bytes, null, contentType);
61 }
62
63 static SimpleBody create(final byte[] body, final ContentType contentType) {
64 Args.notNull(body, "Body");
65 return new SimpleBody(body, null, contentType);
66 }
67
68
69
70
71
72
73 public ContentType getContentType() {
74 return contentType;
75 }
76
77
78
79
80
81
82 public byte[] getBodyBytes() {
83 if (bodyAsBytes != null) {
84 return bodyAsBytes;
85 } else if (bodyAsText != null) {
86 final Charset charset = (contentType != null ? contentType : ContentType.DEFAULT_TEXT).getCharset();
87 return bodyAsText.getBytes(charset != null ? charset : StandardCharsets.US_ASCII);
88 } else {
89 return null;
90 }
91 }
92
93
94
95
96
97
98 public String getBodyText() {
99 if (bodyAsBytes != null) {
100 final Charset charset = (contentType != null ? contentType : ContentType.DEFAULT_TEXT).getCharset();
101 return new String(bodyAsBytes, charset != null ? charset : StandardCharsets.US_ASCII);
102 }
103 return bodyAsText;
104 }
105
106
107
108
109
110
111 public boolean isText() {
112 return bodyAsText != null;
113 }
114
115
116
117
118
119
120 public boolean isBytes() {
121 return bodyAsBytes != null;
122 }
123
124 @Override
125 public String toString() {
126 return "SimpleBody{content length=" + (bodyAsBytes != null ? bodyAsBytes.length : "chunked") +
127 ", content type=" + contentType + "}";
128 }
129
130 }
131