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
29 package org.apache.commons.httpclient.methods.multipart;
30
31 import java.io.IOException;
32 import java.io.OutputStream;
33 import java.util.Random;
34
35 import org.apache.commons.httpclient.methods.RequestEntity;
36 import org.apache.commons.httpclient.params.HttpMethodParams;
37 import org.apache.commons.httpclient.util.EncodingUtil;
38 import org.apache.commons.logging.Log;
39 import org.apache.commons.logging.LogFactory;
40
41 /***
42 * Implements a request entity suitable for an HTTP multipart POST method.
43 * <p>
44 * The HTTP multipart POST method is defined in section 3.3 of
45 * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC1867</a>:
46 * <blockquote>
47 * The media-type multipart/form-data follows the rules of all multipart
48 * MIME data streams as outlined in RFC 1521. The multipart/form-data contains
49 * a series of parts. Each part is expected to contain a content-disposition
50 * header where the value is "form-data" and a name attribute specifies
51 * the field name within the form, e.g., 'content-disposition: form-data;
52 * name="xxxxx"', where xxxxx is the field name corresponding to that field.
53 * Field names originally in non-ASCII character sets may be encoded using
54 * the method outlined in RFC 1522.
55 * </blockquote>
56 * </p>
57 * <p>This entity is designed to be used in conjunction with the
58 * {@link org.apache.commons.httpclient.methods.PostMethod post method} to provide
59 * multipart posts. Example usage:</p>
60 * <code>
61 * File f = new File("/path/fileToUpload.txt");
62 * PostMethod filePost = new PostMethod("http://host/some_path");
63 * Part[] parts = {
64 * new StringPart("param_name", "value"),
65 * new FilePart(f.getName(), f)
66 * };
67 * filePost.setRequestEntity(
68 * new MultipartRequestEntity(parts, filePost.getParams())
69 * );
70 * HttpClient client = new HttpClient();
71 * int status = client.executeMethod(filePost);
72 * </code>
73 *
74 * @since 3.0
75 */
76 public class MultipartRequestEntity implements RequestEntity {
77
78 private static final Log log = LogFactory.getLog(MultipartRequestEntity.class);
79
80 /*** The Content-Type for multipart/form-data. */
81 private static final String MULTIPART_FORM_CONTENT_TYPE = "multipart/form-data";
82
83 /***
84 * The pool of ASCII chars to be used for generating a multipart boundary.
85 */
86 private static byte[] MULTIPART_CHARS = EncodingUtil.getAsciiBytes(
87 "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
88
89 /***
90 * Generates a random multipart boundary string.
91 * @return
92 */
93 private static byte[] generateMultipartBoundary() {
94 Random rand = new Random();
95 byte[] bytes = new byte[rand.nextInt(11) + 30];
96 for (int i = 0; i < bytes.length; i++) {
97 bytes[i] = MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)];
98 }
99 return bytes;
100 }
101
102 /*** The MIME parts as set by the constructor */
103 protected Part[] parts;
104
105 private byte[] multipartBoundary;
106
107 private HttpMethodParams params;
108
109 /***
110 * Creates a new multipart entity containing the given parts.
111 * @param parts The parts to include.
112 * @param params The params of the HttpMethod using this entity.
113 */
114 public MultipartRequestEntity(Part[] parts, HttpMethodParams params) {
115 if (parts == null) {
116 throw new IllegalArgumentException("parts cannot be null");
117 }
118 if (params == null) {
119 throw new IllegalArgumentException("params cannot be null");
120 }
121 this.parts = parts;
122 this.params = params;
123 }
124
125 /***
126 * Returns the MIME boundary string that is used to demarcate boundaries of
127 * this part. The first call to this method will implicitly create a new
128 * boundary string. To create a boundary string first the
129 * HttpMethodParams.MULTIPART_BOUNDARY parameter is considered. Otherwise
130 * a random one is generated.
131 *
132 * @return The boundary string of this entity in ASCII encoding.
133 */
134 protected byte[] getMultipartBoundary() {
135 if (multipartBoundary == null) {
136 String temp = (String) params.getParameter(HttpMethodParams.MULTIPART_BOUNDARY);
137 if (temp != null) {
138 multipartBoundary = EncodingUtil.getAsciiBytes(temp);
139 } else {
140 multipartBoundary = generateMultipartBoundary();
141 }
142 }
143 return multipartBoundary;
144 }
145
146 /***
147 * Returns <code>true</code> if all parts are repeatable, <code>false</code> otherwise.
148 * @see org.apache.commons.httpclient.methods.RequestEntity#isRepeatable()
149 */
150 public boolean isRepeatable() {
151 for (int i = 0; i < parts.length; i++) {
152 if (!parts[i].isRepeatable()) {
153 return false;
154 }
155 }
156 return true;
157 }
158
159
160
161
162 public void writeRequest(OutputStream out) throws IOException {
163 Part.sendParts(out, parts, getMultipartBoundary());
164 }
165
166
167
168
169 public long getContentLength() {
170 try {
171 return Part.getLengthOfParts(parts, getMultipartBoundary());
172 } catch (Exception e) {
173 log.error("An exception occurred while getting the length of the parts", e);
174 return 0;
175 }
176 }
177
178
179
180
181 public String getContentType() {
182 StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
183 buffer.append("; boundary=");
184 buffer.append(EncodingUtil.getAsciiString(getMultipartBoundary()));
185 return buffer.toString();
186 }
187
188 }