View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.http.util;
29  
30  import java.io.IOException;
31  import java.io.InputStream;
32  import java.io.InputStreamReader;
33  import java.io.Reader;
34  import java.io.UnsupportedEncodingException;
35  import java.nio.charset.Charset;
36  import java.nio.charset.UnsupportedCharsetException;
37  
38  import org.apache.http.HeaderElement;
39  import org.apache.http.HttpEntity;
40  import org.apache.http.HttpResponse;
41  import org.apache.http.NameValuePair;
42  import org.apache.http.ParseException;
43  import org.apache.http.entity.ContentType;
44  import org.apache.http.protocol.HTTP;
45  
46  /**
47   * Static helpers for dealing with {@link HttpEntity}s.
48   *
49   * @since 4.0
50   */
51  public final class EntityUtils {
52  
53      private EntityUtils() {
54      }
55  
56      /**
57       * Ensures that the entity content is fully consumed and the content stream, if exists,
58       * is closed. The process is done, <i>quietly</i> , without throwing any IOException.
59       *
60       * @param entity the entity to consume.
61       *
62       *
63       * @since 4.2
64       */
65      public static void consumeQuietly(final HttpEntity entity) {
66          try {
67            consume(entity);
68          } catch (final IOException ignore) {
69          }
70      }
71  
72      /**
73       * Ensures that the entity content is fully consumed and the content stream, if exists,
74       * is closed.
75       *
76       * @param entity the entity to consume.
77       * @throws IOException if an error occurs reading the input stream
78       *
79       * @since 4.1
80       */
81      public static void consume(final HttpEntity entity) throws IOException {
82          if (entity == null) {
83              return;
84          }
85          if (entity.isStreaming()) {
86              final InputStream instream = entity.getContent();
87              if (instream != null) {
88                  instream.close();
89              }
90          }
91      }
92  
93      /**
94       * Updates an entity in a response by first consuming an existing entity, then setting the new one.
95       *
96       * @param response the response with an entity to update; must not be null.
97       * @param entity the entity to set in the response.
98       * @throws IOException if an error occurs while reading the input stream on the existing
99       * entity.
100      * @throws IllegalArgumentException if response is null.
101      *
102      * @since 4.3
103      */
104     public static void updateEntity(
105             final HttpResponse response, final HttpEntity entity) throws IOException {
106         Args.notNull(response, "Response");
107         consume(response.getEntity());
108         response.setEntity(entity);
109     }
110 
111     /**
112      * Read the contents of an entity and return it as a byte array.
113      *
114      * @param entity the entity to read from=
115      * @return byte array containing the entity content. May be null if
116      *   {@link HttpEntity#getContent()} is null.
117      * @throws IOException if an error occurs reading the input stream
118      * @throws IllegalArgumentException if entity is null or if content length &gt; Integer.MAX_VALUE
119      */
120     public static byte[] toByteArray(final HttpEntity entity) throws IOException {
121         Args.notNull(entity, "Entity");
122         final InputStream instream = entity.getContent();
123         if (instream == null) {
124             return null;
125         }
126         try {
127             Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
128                     "HTTP entity too large to be buffered in memory");
129             int i = (int)entity.getContentLength();
130             if (i < 0) {
131                 i = 4096;
132             }
133             final ByteArrayBuffer buffer = new ByteArrayBuffer(i);
134             final byte[] tmp = new byte[4096];
135             int l;
136             while((l = instream.read(tmp)) != -1) {
137                 buffer.append(tmp, 0, l);
138             }
139             return buffer.toByteArray();
140         } finally {
141             instream.close();
142         }
143     }
144 
145     /**
146      * Obtains character set of the entity, if known.
147      *
148      * @param entity must not be null
149      * @return the character set, or null if not found
150      * @throws ParseException if header elements cannot be parsed
151      * @throws IllegalArgumentException if entity is null
152      *
153      * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)}
154      */
155     @Deprecated
156     public static String getContentCharSet(final HttpEntity entity) throws ParseException {
157         Args.notNull(entity, "Entity");
158         String charset = null;
159         if (entity.getContentType() != null) {
160             final HeaderElement values[] = entity.getContentType().getElements();
161             if (values.length > 0) {
162                 final NameValuePair param = values[0].getParameterByName("charset");
163                 if (param != null) {
164                     charset = param.getValue();
165                 }
166             }
167         }
168         return charset;
169     }
170 
171     /**
172      * Obtains MIME type of the entity, if known.
173      *
174      * @param entity must not be null
175      * @return the character set, or null if not found
176      * @throws ParseException if header elements cannot be parsed
177      * @throws IllegalArgumentException if entity is null
178      *
179      * @since 4.1
180      *
181      * @deprecated (4.1.3) use {@link ContentType#getOrDefault(HttpEntity)}
182      */
183     @Deprecated
184     public static String getContentMimeType(final HttpEntity entity) throws ParseException {
185         Args.notNull(entity, "Entity");
186         String mimeType = null;
187         if (entity.getContentType() != null) {
188             final HeaderElement values[] = entity.getContentType().getElements();
189             if (values.length > 0) {
190                 mimeType = values[0].getName();
191             }
192         }
193         return mimeType;
194     }
195 
196     /**
197      * Get the entity content as a String, using the provided default character set
198      * if none is found in the entity.
199      * If defaultCharset is null, the default "ISO-8859-1" is used.
200      *
201      * @param entity must not be null
202      * @param defaultCharset character set to be applied if none found in the entity,
203      * or if the entity provided charset is invalid or not available.
204      * @return the entity content as a String. May be null if
205      *   {@link HttpEntity#getContent()} is null.
206      * @throws ParseException if header elements cannot be parsed
207      * @throws IllegalArgumentException if entity is null or if content length &gt; Integer.MAX_VALUE
208      * @throws IOException if an error occurs reading the input stream
209      * @throws UnsupportedCharsetException Thrown when the named entity's charset is not available in
210      * this instance of the Java virtual machine and no defaultCharset is provided.
211      */
212     public static String toString(
213             final HttpEntity entity, final Charset defaultCharset) throws IOException, ParseException {
214         Args.notNull(entity, "Entity");
215         final InputStream instream = entity.getContent();
216         if (instream == null) {
217             return null;
218         }
219         try {
220             Args.check(entity.getContentLength() <= Integer.MAX_VALUE,
221                     "HTTP entity too large to be buffered in memory");
222             int i = (int)entity.getContentLength();
223             if (i < 0) {
224                 i = 4096;
225             }
226             Charset charset = null;
227             try {
228                 final ContentType contentType = ContentType.get(entity);
229                 if (contentType != null) {
230                     charset = contentType.getCharset();
231                 }
232             } catch (final UnsupportedCharsetException ex) {
233                 if (defaultCharset == null) {
234                     throw new UnsupportedEncodingException(ex.getMessage());
235                 }
236             }
237             if (charset == null) {
238                 charset = defaultCharset;
239             }
240             if (charset == null) {
241                 charset = HTTP.DEF_CONTENT_CHARSET;
242             }
243             final Reader reader = new InputStreamReader(instream, charset);
244             final CharArrayBuffer buffer = new CharArrayBuffer(i);
245             final char[] tmp = new char[1024];
246             int l;
247             while((l = reader.read(tmp)) != -1) {
248                 buffer.append(tmp, 0, l);
249             }
250             return buffer.toString();
251         } finally {
252             instream.close();
253         }
254     }
255 
256     /**
257      * Get the entity content as a String, using the provided default character set
258      * if none is found in the entity.
259      * If defaultCharset is null, the default "ISO-8859-1" is used.
260      *
261      * @param entity must not be null
262      * @param defaultCharset character set to be applied if none found in the entity
263      * @return the entity content as a String. May be null if
264      *   {@link HttpEntity#getContent()} is null.
265      * @throws ParseException if header elements cannot be parsed
266      * @throws IllegalArgumentException if entity is null or if content length &gt; Integer.MAX_VALUE
267      * @throws IOException if an error occurs reading the input stream
268      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
269      * this instance of the Java virtual machine
270      */
271     public static String toString(
272             final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
273         return toString(entity, defaultCharset != null ? Charset.forName(defaultCharset) : null);
274     }
275 
276     /**
277      * Read the contents of an entity and return it as a String.
278      * The content is converted using the character set from the entity (if any),
279      * failing that, "ISO-8859-1" is used.
280      *
281      * @param entity the entity to convert to a string; must not be null
282      * @return String containing the content.
283      * @throws ParseException if header elements cannot be parsed
284      * @throws IllegalArgumentException if entity is null or if content length &gt; Integer.MAX_VALUE
285      * @throws IOException if an error occurs reading the input stream
286      * @throws UnsupportedCharsetException Thrown when the named charset is not available in
287      * this instance of the Java virtual machine
288      */
289     public static String toString(final HttpEntity entity)
290         throws IOException, ParseException {
291         return toString(entity, (Charset)null);
292     }
293 
294 }