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 com.foxinmy.weixin4j.http.apache.mime;
29
30 import com.foxinmy.weixin4j.http.ContentType;
31 import com.foxinmy.weixin4j.http.apache.content.AbstractContentBody;
32 import com.foxinmy.weixin4j.http.apache.content.ContentBody;
33
34
35
36
37
38
39
40
41 public class FormBodyPart {
42
43 private final String name;
44 private final Header header;
45 private final ContentBody body;
46
47 FormBodyPart(final String name, final ContentBody body, final Header header) {
48 super();
49 this.name = name;
50 this.body = body;
51 this.header = header != null ? header : new Header();
52 }
53
54
55
56
57 public FormBodyPart(final String name, final ContentBody body) {
58 super();
59 this.name = name;
60 this.body = body;
61 this.header = new Header();
62
63 generateContentDisp(body);
64 generateContentType(body);
65 generateTransferEncoding(body);
66 }
67
68 public String getName() {
69 return this.name;
70 }
71
72 public ContentBody getBody() {
73 return this.body;
74 }
75
76 public Header getHeader() {
77 return this.header;
78 }
79
80 public void addField(final String name, final String value) {
81 this.header.addField(new MinimalField(name, value));
82 }
83
84
85
86
87 protected void generateContentDisp(final ContentBody body) {
88 final StringBuilder buffer = new StringBuilder();
89 buffer.append("form-data; name=\"");
90 buffer.append(getName());
91 buffer.append("\"");
92 if (body.getFilename() != null) {
93 buffer.append("; filename=\"");
94 buffer.append(body.getFilename());
95 buffer.append("\"");
96 }
97 addField(MIME.CONTENT_DISPOSITION, buffer.toString());
98 }
99
100
101
102
103 protected void generateContentType(final ContentBody body) {
104 final ContentType contentType;
105 if (body instanceof AbstractContentBody) {
106 contentType = ((AbstractContentBody) body).getContentType();
107 } else {
108 contentType = null;
109 }
110 if (contentType != null) {
111 addField(MIME.CONTENT_TYPE, contentType.toString());
112 } else {
113 final StringBuilder buffer = new StringBuilder();
114 buffer.append(body.getMimeType());
115 if (body.getCharset() != null) {
116 buffer.append("; charset=");
117 buffer.append(body.getCharset());
118 }
119 addField(MIME.CONTENT_TYPE, buffer.toString());
120 }
121 }
122
123
124
125
126 protected void generateTransferEncoding(final ContentBody body) {
127 addField(MIME.CONTENT_TRANSFER_ENC, body.getTransferEncoding());
128 }
129 }