MultipartEntity.java revision 823675fdbb7f974b8e2fa9fbb71774b32487582d
1/*
2 * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/MultipartRequestEntity.java,v 1.1 2004/10/06 03:39:59 mbecke Exp $
3 * $Revision: 502647 $
4 * $Date: 2007-02-02 17:22:54 +0100 (Fri, 02 Feb 2007) $
5 *
6 * ====================================================================
7 *
8 *  Licensed to the Apache Software Foundation (ASF) under one or more
9 *  contributor license agreements.  See the NOTICE file distributed with
10 *  this work for additional information regarding copyright ownership.
11 *  The ASF licenses this file to You under the Apache License, Version 2.0
12 *  (the "License"); you may not use this file except in compliance with
13 *  the License.  You may obtain a copy of the License at
14 *
15 *      http://www.apache.org/licenses/LICENSE-2.0
16 *
17 *  Unless required by applicable law or agreed to in writing, software
18 *  distributed under the License is distributed on an "AS IS" BASIS,
19 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 *  See the License for the specific language governing permissions and
21 *  limitations under the License.
22 * ====================================================================
23 *
24 * This software consists of voluntary contributions made by many
25 * individuals on behalf of the Apache Software Foundation.  For more
26 * information on the Apache Software Foundation, please see
27 * <http://www.apache.org/>.
28 *
29 */
30
31package com.android.internal.http.multipart;
32
33import java.io.ByteArrayInputStream;
34import java.io.ByteArrayOutputStream;
35import java.io.IOException;
36import java.io.InputStream;
37import java.io.OutputStream;
38import java.util.Random;
39
40import org.apache.http.Header;
41import org.apache.http.entity.AbstractHttpEntity;
42import org.apache.http.message.BasicHeader;
43import org.apache.http.params.HttpParams;
44import org.apache.http.protocol.HTTP;
45import org.apache.http.util.EncodingUtils;
46import org.apache.commons.logging.Log;
47import org.apache.commons.logging.LogFactory;
48
49/**
50 * Implements a request entity suitable for an HTTP multipart POST method.
51 * <p>
52 * The HTTP multipart POST method is defined in section 3.3 of
53 * <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC1867</a>:
54 * <blockquote>
55 * The media-type multipart/form-data follows the rules of all multipart
56 * MIME data streams as outlined in RFC 1521. The multipart/form-data contains
57 * a series of parts. Each part is expected to contain a content-disposition
58 * header where the value is "form-data" and a name attribute specifies
59 * the field name within the form, e.g., 'content-disposition: form-data;
60 * name="xxxxx"', where xxxxx is the field name corresponding to that field.
61 * Field names originally in non-ASCII character sets may be encoded using
62 * the method outlined in RFC 1522.
63 * </blockquote>
64 * </p>
65 * <p>This entity is designed to be used in conjunction with the
66 * {@link org.apache.http.HttpRequest} to provide
67 * multipart posts.  Example usage:</p>
68 * <pre>
69 *  File f = new File("/path/fileToUpload.txt");
70 *  HttpRequest request = new HttpRequest("http://host/some_path");
71 *  Part[] parts = {
72 *      new StringPart("param_name", "value"),
73 *      new FilePart(f.getName(), f)
74 *  };
75 *  filePost.setEntity(
76 *      new MultipartRequestEntity(parts, filePost.getParams())
77 *      );
78 *  HttpClient client = new HttpClient();
79 *  int status = client.executeMethod(filePost);
80 * </pre>
81 *
82 * @since 3.0
83 *
84 * @deprecated Please use {@link java.net.URLConnection} and friends instead.
85 *     The Apache HTTP client is no longer maintained and may be removed in a future
86 *     release. Please visit <a href="http://android-developers.blogspot.com/2011/09/androids-http-clients.html">this webpage</a>
87 *     for further details.
88 */
89@Deprecated
90public class MultipartEntity extends AbstractHttpEntity {
91
92    private static final Log log = LogFactory.getLog(MultipartEntity.class);
93
94    /** The Content-Type for multipart/form-data. */
95    private static final String MULTIPART_FORM_CONTENT_TYPE = "multipart/form-data";
96
97    /**
98     * Sets the value to use as the multipart boundary.
99     * <p>
100     * This parameter expects a value if type {@link String}.
101     * </p>
102     */
103    public static final String MULTIPART_BOUNDARY = "http.method.multipart.boundary";
104
105    /**
106     * The pool of ASCII chars to be used for generating a multipart boundary.
107     */
108    private static byte[] MULTIPART_CHARS = EncodingUtils.getAsciiBytes(
109        "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
110
111    /**
112     * Generates a random multipart boundary string.
113    */
114    private static byte[] generateMultipartBoundary() {
115        Random rand = new Random();
116        byte[] bytes = new byte[rand.nextInt(11) + 30]; // a random size from 30 to 40
117        for (int i = 0; i < bytes.length; i++) {
118            bytes[i] = MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)];
119        }
120        return bytes;
121    }
122
123    /** The MIME parts as set by the constructor */
124    protected Part[] parts;
125
126    private byte[] multipartBoundary;
127
128    private HttpParams params;
129
130    private boolean contentConsumed = false;
131
132    /**
133     * Creates a new multipart entity containing the given parts.
134     * @param parts The parts to include.
135     * @param params The params of the HttpMethod using this entity.
136     */
137    public MultipartEntity(Part[] parts, HttpParams params) {
138      if (parts == null) {
139          throw new IllegalArgumentException("parts cannot be null");
140      }
141      if (params == null) {
142          throw new IllegalArgumentException("params cannot be null");
143      }
144      this.parts = parts;
145      this.params = params;
146    }
147
148    public MultipartEntity(Part[] parts) {
149      setContentType(MULTIPART_FORM_CONTENT_TYPE);
150      if (parts == null) {
151          throw new IllegalArgumentException("parts cannot be null");
152      }
153      this.parts = parts;
154      this.params = null;
155    }
156
157    /**
158     * Returns the MIME boundary string that is used to demarcate boundaries of
159     * this part. The first call to this method will implicitly create a new
160     * boundary string. To create a boundary string first the
161     * HttpMethodParams.MULTIPART_BOUNDARY parameter is considered. Otherwise
162     * a random one is generated.
163     *
164     * @return The boundary string of this entity in ASCII encoding.
165     */
166    protected byte[] getMultipartBoundary() {
167        if (multipartBoundary == null) {
168            String temp = null;
169            if (params != null) {
170              temp = (String) params.getParameter(MULTIPART_BOUNDARY);
171            }
172            if (temp != null) {
173                multipartBoundary = EncodingUtils.getAsciiBytes(temp);
174            } else {
175                multipartBoundary = generateMultipartBoundary();
176            }
177        }
178        return multipartBoundary;
179    }
180
181    /**
182     * Returns <code>true</code> if all parts are repeatable, <code>false</code> otherwise.
183     */
184    public boolean isRepeatable() {
185        for (int i = 0; i < parts.length; i++) {
186            if (!parts[i].isRepeatable()) {
187                return false;
188            }
189        }
190        return true;
191    }
192
193    /* (non-Javadoc)
194     */
195    public void writeTo(OutputStream out) throws IOException {
196        Part.sendParts(out, parts, getMultipartBoundary());
197    }
198    /* (non-Javadoc)
199     * @see org.apache.commons.http.AbstractHttpEntity.#getContentType()
200     */
201    @Override
202    public Header getContentType() {
203      StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
204      buffer.append("; boundary=");
205      buffer.append(EncodingUtils.getAsciiString(getMultipartBoundary()));
206      return new BasicHeader(HTTP.CONTENT_TYPE, buffer.toString());
207
208    }
209
210    /* (non-Javadoc)
211     */
212    public long getContentLength() {
213        try {
214            return Part.getLengthOfParts(parts, getMultipartBoundary());
215        } catch (Exception e) {
216            log.error("An exception occurred while getting the length of the parts", e);
217            return 0;
218        }
219    }
220
221    public InputStream getContent() throws IOException, IllegalStateException {
222          if(!isRepeatable() && this.contentConsumed ) {
223              throw new IllegalStateException("Content has been consumed");
224          }
225          this.contentConsumed = true;
226
227          ByteArrayOutputStream baos = new ByteArrayOutputStream();
228          Part.sendParts(baos, this.parts, this.multipartBoundary);
229          ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
230          return bais;
231    }
232
233    public boolean isStreaming() {
234        return false;
235    }
236}
237