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.util.List;
31
32 import org.apache.hc.core5.http.ContentType;
33 import org.apache.hc.core5.http.NameValuePair;
34 import org.apache.hc.core5.util.Args;
35 import org.apache.hc.core5.util.Asserts;
36
37
38
39
40
41
42 public class MultipartPartBuilder {
43
44 private ContentBody body;
45 private final Header header;
46
47 public static MultipartPartBuilder create(final ContentBody body) {
48 return new MultipartPartBuilder(body);
49 }
50
51 public static MultipartPartBuilder create() {
52 return new MultipartPartBuilder();
53 }
54
55 MultipartPartBuilder(final ContentBody body) {
56 this();
57 this.body = body;
58 }
59
60 MultipartPartBuilder() {
61 this.header = new Header();
62 }
63
64 public MultipartPartBuilder setBody(final ContentBody body) {
65 this.body = body;
66 return this;
67 }
68
69 public MultipartPartBuilder addHeader(final String name, final String value, final List<NameValuePair> parameters) {
70 Args.notNull(name, "Header name");
71 this.header.addField(new MimeField(name, value, parameters));
72 return this;
73 }
74
75 public MultipartPartBuilder addHeader(final String name, final String value) {
76 Args.notNull(name, "Header name");
77 this.header.addField(new MimeField(name, value));
78 return this;
79 }
80
81 public MultipartPartBuilder setHeader(final String name, final String value) {
82 Args.notNull(name, "Header name");
83 this.header.setField(new MimeField(name, value));
84 return this;
85 }
86
87 public MultipartPartBuilder removeHeaders(final String name) {
88 Args.notNull(name, "Header name");
89 this.header.removeFields(name);
90 return this;
91 }
92
93 public MultipartPart build() {
94 Asserts.notNull(this.body, "Content body");
95 final Header headerCopy = new Header();
96 final List<MimeField> fields = this.header.getFields();
97 for (final MimeField field: fields) {
98 headerCopy.addField(field);
99 }
100 if (headerCopy.getField(MimeConsts.CONTENT_TYPE) == null) {
101 final ContentType contentType;
102 if (body instanceof AbstractContentBody) {
103 contentType = ((AbstractContentBody) body).getContentType();
104 } else {
105 contentType = null;
106 }
107 if (contentType != null) {
108 headerCopy.addField(new MimeField(MimeConsts.CONTENT_TYPE, contentType.toString()));
109 } else {
110 final StringBuilder buffer = new StringBuilder();
111 buffer.append(this.body.getMimeType());
112 if (this.body.getCharset() != null) {
113 buffer.append("; charset=");
114 buffer.append(this.body.getCharset());
115 }
116 headerCopy.addField(new MimeField(MimeConsts.CONTENT_TYPE, buffer.toString()));
117 }
118 }
119 return new MultipartPart(this.body, headerCopy);
120 }
121 }