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 private Part[] parts;
103
104 private byte[] multipartBoundary;
105
106 private HttpMethodParams params;
107
108 /***
109 * Creates a new multipart entity containing the given parts.
110 * @param parts The parts to include.
111 * @param params The params of the HttpMethod using this entity.
112 */
113 public MultipartRequestEntity(Part[] parts, HttpMethodParams params) {
114 if (parts == null) {
115 throw new IllegalArgumentException("parts cannot be null");
116 }
117 if (params == null) {
118 throw new IllegalArgumentException("params cannot be null");
119 }
120 this.parts = parts;
121 this.params = params;
122 }
123
124 private byte[] getMultipartBoundary() {
125 if (multipartBoundary == null) {
126 String temp = (String) params.getParameter(HttpMethodParams.MULTIPART_BOUNDARY);
127 if (temp != null) {
128 multipartBoundary = EncodingUtil.getAsciiBytes(temp);
129 } else {
130 multipartBoundary = generateMultipartBoundary();
131 }
132 }
133 return multipartBoundary;
134 }
135
136 /***
137 * Returns <code>true</code> if all parts are repeatable, <code>false</code> otherwise.
138 * @see org.apache.commons.httpclient.methods.RequestEntity#isRepeatable()
139 */
140 public boolean isRepeatable() {
141 for (int i = 0; i < parts.length; i++) {
142 if (!parts[i].isRepeatable()) {
143 return false;
144 }
145 }
146 return true;
147 }
148
149
150
151
152 public void writeRequest(OutputStream out) throws IOException {
153 Part.sendParts(out, parts, getMultipartBoundary());
154 }
155
156
157
158
159 public long getContentLength() {
160 try {
161 return Part.getLengthOfParts(parts, getMultipartBoundary());
162 } catch (Exception e) {
163 log.error("An exception occurred while getting the length of the parts", e);
164 return 0;
165 }
166 }
167
168
169
170
171 public String getContentType() {
172 StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
173 buffer.append("; boundary=");
174 buffer.append(EncodingUtil.getAsciiString(getMultipartBoundary()));
175 return buffer.toString();
176 }
177
178 }