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 public ContentType getContentType() {
69 return contentType;
70 }
71
72 public byte[] getBodyBytes() {
73 if (bodyAsBytes != null) {
74 return bodyAsBytes;
75 } else if (bodyAsText != null) {
76 final Charset charset = (contentType != null ? contentType : ContentType.DEFAULT_TEXT).getCharset();
77 return bodyAsText.getBytes(charset != null ? charset : StandardCharsets.US_ASCII);
78 } else {
79 return null;
80 }
81 }
82
83 public String getBodyText() {
84 if (bodyAsBytes != null) {
85 final Charset charset = (contentType != null ? contentType : ContentType.DEFAULT_TEXT).getCharset();
86 return new String(bodyAsBytes, charset != null ? charset : StandardCharsets.US_ASCII);
87 } else {
88 return bodyAsText;
89 }
90 }
91
92 public boolean isText() {
93 return bodyAsText != null;
94 }
95
96 public boolean isBytes() {
97 return bodyAsBytes != null;
98 }
99
100 @Override
101 public String toString() {
102 return "SimpleBody{content length=" + (bodyAsBytes != null ? bodyAsBytes.length : "chunked") +
103 ", content type=" + contentType + "}";
104 }
105
106 }
107