HttpEntity的類型及其使用

1  BasicHttpEntity

      代表底層流的基本實體。通常是在http報文中獲取的實體。他只有一個空參的構造方法。剛創建時沒有內容,長度爲負值。需要通過兩個方法,把值賦進去。

[java] view plaincopy
  1. /** 
  2.   * BasicHttpEntity 
  3.   * @throws IOException 
  4.   */  
  5.  public static void testBasicHttpEntity() throws IOException{  
  6.   InputStream is = null;  
  7.   //BasicHttpEntity這類就是一個輸入流的內容包裝類,包裝內容的相關的編碼格式,長度等  
  8.   BasicHttpEntity entity = new BasicHttpEntity();  
  9.   //設置內容  
  10.   entity.setContent(is);  
  11.   //設置長度  
  12.   entity.setContentLength(is.available());  
  13.   //沒搞懂chunked這個屬性啥意思  
  14.   entity.setChunked(false);  
  15.  }  

2  ByteArrayEntity

    是自我包含的,可重複獲得使用的,從指定的字節數組中取出內容的實體。字節數組是這個實體的構造方法的參數。

[java] view plaincopy
  1. /** 
  2.   * ByteArrayEntity 
  3.   * @throws IOException 
  4.   */  
  5.  public static void testByteArrayEntity() throws IOException{  
  6.   ByteArrayEntity entity = new ByteArrayEntity("內容".getBytes());  
  7.   ByteArrayInputStream is = (ByteArrayInputStream) entity.getContent();  
  8.   //上面這行代碼返回的其實是一個ByteArrayInputStream對象  
  9.   /*public InputStream getContent() { 
  10.          return new ByteArrayInputStream(this.b, this.off, this.len); 
  11.      }*/  
  12.  }  

3  StringEntity

    是自我包含的可重複的實體。通過String創建的實體。有兩個構造方法,一個是自Sring爲參數的構造方法,一個是以String和字符編碼爲參數的構造方法。

[java] view plaincopy
  1. /** 
  2.   * StringEntity 
  3.   * @throws IOException 
  4.   */  
  5.  public static void testStringEntity() throws IOException{  
  6.    StringBuilder sb = new StringBuilder();  
  7.    //獲取系統的信息集合,這個集合是不可以修改的  
  8.    Map<String, String> nev = System.getenv();  
  9.    for(Entry<String, String> entry : nev.entrySet()){  
  10.     sb.append(entry.getKey()).append("=")  
  11.     .append(entry.getValue()).append("\n");  
  12.    }  
  13.    String content = sb.toString();  
  14.    System.out.println(content);  
  15.    //創建只帶字符串參數的  
  16.    StringEntity entity = new StringEntity(content);  
  17.    //創建帶字符創參數和字符編碼的  
  18.    StringEntity entity2 = new StringEntity(content, "UTF-8");  
  19.      
  20.  }  

4  InputreamEntity

    是流式不可以重複的實體。構造方法是InputStream 和內容長度,內容長度是輸入流的長度。

[java] view plaincopy
  1. /** 
  2.   * InputStreamEntity 
  3.   * @throws IOException 
  4.   */  
  5.  public static void testInputStreamEntity() throws IOException{  
  6.   InputStream is = null;  
  7.   //InputStreamEntity嚴格是對內容和長度相匹配的。用法和BasicHttpEntity類似  
  8.   InputStreamEntity entity = new InputStreamEntity(is, is.available());  
  9.  }  

5  FileEntity

    自我包含式,可以重複的實體。參數傳入文件和文件類型。

[java] view plaincopy
  1. /** 
  2.   * FileEntity 
  3.   * @throws IOException 
  4.   */  
  5.  public static void testFileEntity() throws IOException{  
  6.    FileEntity entity = new FileEntity(new File(""), ContentType.APPLICATION_FORM_URLENCODED);  
  7.    FileEntity entity2 = new FileEntity(new File(""), "application/java-achive");  
  8.      
  9.  }  

6  EntityTemplete

    從ContentProducer接口接受內容的實體。在ContentProducer的實現類中寫入想要寫入的內容。

[java] view plaincopy
  1. /** 
  2.   * EntityTemplate 
  3.   * @throws IOException 
  4.   */  
  5.  public static void testEntityTemplate() throws IOException{  
  6.   ContentProducer producer = new ContentProducer() {  
  7.      
  8.    @Override  
  9.    public void writeTo(OutputStream outstream) throws IOException {  
  10.     outstream.write("這是什麼東東》。".getBytes());  
  11.    }  
  12.   };  
  13.     
  14.   EntityTemplate entity = new EntityTemplate(producer);  
  15.   entity.writeTo(System.out);  
  16.  }  

7  HttpEntityWrapper

      這個是創建被包裝實體的基類,有被包裝實體的引用。相當於實體的代理類,被包裝實體是他的一個屬性。下面是這個類的源碼:

[java] view plaincopy
  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.entity;  
  29.   
  30. import java.io.IOException;  
  31. import java.io.InputStream;  
  32. import java.io.OutputStream;  
  33.   
  34. import org.apache.http.Header;  
  35. import org.apache.http.HttpEntity;  
  36. import org.apache.http.annotation.NotThreadSafe;  
  37.   
  38. /** 
  39.  * Base class for wrapping entities. 
  40.  * Keeps a {@link #wrappedEntity wrappedEntity} and delegates all 
  41.  * calls to it. Implementations of wrapping entities can derive 
  42.  * from this class and need to override only those methods that 
  43.  * should not be delegated to the wrapped entity. 
  44.  * 
  45.  * @since 4.0 
  46.  */  
  47. @NotThreadSafe  
  48. public class HttpEntityWrapper implements HttpEntity {  
  49.   
  50.     /** The wrapped entity. */  
  51.     protected HttpEntity wrappedEntity;  
  52.   
  53.     /** 
  54.      * Creates a new entity wrapper. 
  55.      * 
  56.      * @param wrapped   the entity to wrap, not null 
  57.      * @throws IllegalArgumentException if wrapped is null 
  58.      */  
  59.     public HttpEntityWrapper(HttpEntity wrapped) {  
  60.         super();  
  61.   
  62.         if (wrapped == null) {  
  63.             throw new IllegalArgumentException  
  64.                 ("wrapped entity must not be null");  
  65.         }  
  66.         wrappedEntity = wrapped;  
  67.   
  68.     } // constructor  
  69.   
  70.   
  71.     public boolean isRepeatable() {  
  72.         return wrappedEntity.isRepeatable();  
  73.     }  
  74.   
  75.     public boolean isChunked() {  
  76.         return wrappedEntity.isChunked();  
  77.     }  
  78.   
  79.     public long getContentLength() {  
  80.         return wrappedEntity.getContentLength();  
  81.     }  
  82.   
  83.     public Header getContentType() {  
  84.         return wrappedEntity.getContentType();  
  85.     }  
  86.   
  87.     public Header getContentEncoding() {  
  88.         return wrappedEntity.getContentEncoding();  
  89.     }  
  90.   
  91.     public InputStream getContent()  
  92.         throws IOException {  
  93.         return wrappedEntity.getContent();  
  94.     }  
  95.   
  96.     public void writeTo(OutputStream outstream)  
  97.         throws IOException {  
  98.         wrappedEntity.writeTo(outstream);  
  99.     }  
  100.   
  101.     public boolean isStreaming() {  
  102.         return wrappedEntity.isStreaming();  
  103.     }  
  104.   
  105.     /** 
  106.      * @deprecated (4.1) Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; 
  107.      * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources. 
  108.      */  
  109.     @Deprecated  
  110.     public void consumeContent() throws IOException {  
  111.         wrappedEntity.consumeContent();  
  112.     }  
  113.   
  114. }  

8  BufferedHttpEntity

    是HttpEntityWarpper的子類,可以把不可以重複的實體,實現成可以重複的實體。它從提供的實體中讀取內容,緩存到內容中。源碼如下:

[java] view plaincopy
  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.entity;  
  29.   
  30. import java.io.ByteArrayInputStream;  
  31. import java.io.IOException;  
  32. import java.io.InputStream;  
  33. import java.io.OutputStream;  
  34.   
  35. import org.apache.http.HttpEntity;  
  36. import org.apache.http.annotation.NotThreadSafe;  
  37. import org.apache.http.util.EntityUtils;  
  38.   
  39. /** 
  40.  * A wrapping entity that buffers it content if necessary. 
  41.  * The buffered entity is always repeatable. 
  42.  * If the wrapped entity is repeatable itself, calls are passed through. 
  43.  * If the wrapped entity is not repeatable, the content is read into a 
  44.  * buffer once and provided from there as often as required. 
  45.  * 
  46.  * @since 4.0 
  47.  */  
  48. @NotThreadSafe  
  49. public class BufferedHttpEntity extends HttpEntityWrapper {  
  50.   
  51.     private final byte[] buffer;  
  52.   
  53.     /** 
  54.      * Creates a new buffered entity wrapper. 
  55.      * 
  56.      * @param entity   the entity to wrap, not null 
  57.      * @throws IllegalArgumentException if wrapped is null 
  58.      */  
  59.     public BufferedHttpEntity(final HttpEntity entity) throws IOException {  
  60.         super(entity);  
  61.         if (!entity.isRepeatable() || entity.getContentLength() < 0) {  
  62.             this.buffer = EntityUtils.toByteArray(entity);  
  63.         } else {  
  64.             this.buffer = null;  
  65.         }  
  66.     }  
  67.   
  68.     @Override  
  69.     public long getContentLength() {  
  70.         if (this.buffer != null) {  
  71.             return this.buffer.length;  
  72.         } else {  
  73.             return wrappedEntity.getContentLength();  
  74.         }  
  75.     }  
  76.   
  77.     @Override  
  78.     public InputStream getContent() throws IOException {  
  79.         if (this.buffer != null) {  
  80.             return new ByteArrayInputStream(this.buffer);  
  81.         } else {  
  82.             return wrappedEntity.getContent();  
  83.         }  
  84.     }  
  85.   
  86.     /** 
  87.      * Tells that this entity does not have to be chunked. 
  88.      * 
  89.      * @return  <code>false</code> 
  90.      */  
  91.     @Override  
  92.     public boolean isChunked() {  
  93.         return (buffer == null) && wrappedEntity.isChunked();  
  94.     }  
  95.   
  96.     /** 
  97.      * Tells that this entity is repeatable. 
  98.      * 
  99.      * @return  <code>true</code> 
  100.      */  
  101.     @Override  
  102.     public boolean isRepeatable() {  
  103.         return true;  
  104.     }  
  105.   
  106.   
  107.     @Override  
  108.     public void writeTo(final OutputStream outstream) throws IOException {  
  109.         if (outstream == null) {  
  110.             throw new IllegalArgumentException("Output stream may not be null");  
  111.         }  
  112.         if (this.buffer != null) {  
  113.             outstream.write(this.buffer);  
  114.         } else {  
  115.             wrappedEntity.writeTo(outstream);  
  116.         }  
  117.     }  
  118.   
  119.   
  120.     // non-javadoc, see interface HttpEntity  
  121.     @Override  
  122.     public boolean isStreaming() {  
  123.         return (buffer == null) && wrappedEntity.isStreaming();  
  124.     }  
  125.   
  126. // class BufferedHttpEntity  

二 HttpEntity 的使用

 

1  HttpEntity實體即可以使流也可以使字符串形式。具體有什麼用法看他的方法解釋:

[java] view plaincopy
  1. package com.scl.base;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.UnsupportedEncodingException;  
  5.   
  6. import org.apache.http.HttpEntity;  
  7. import org.apache.http.ParseException;  
  8. import org.apache.http.entity.StringEntity;  
  9. import org.apache.http.util.EntityUtils;  
  10.   
  11. public class HttpClientDemo06 {  
  12.   
  13.     /** 
  14.      * @param args 
  15.      */  
  16.     public static void main(String[] args) {  
  17.         try {  
  18.             HttpEntity entity = new StringEntity("這一個字符串實體""UTF-8");  
  19.             //內容類型  
  20.             System.out.println(entity.getContentType());  
  21.             //內容的編碼格式  
  22.             System.out.println(entity.getContentEncoding());  
  23.             //內容的長度  
  24.             System.out.println(entity.getContentLength());  
  25.             //把內容轉成字符串  
  26.             System.out.println(EntityUtils.toString(entity));  
  27.             //內容轉成字節數組  
  28.             System.out.println(EntityUtils.toByteArray(entity).length);  
  29.             //還有個直接獲得流  
  30.             //entity.getContent();  
  31.         } catch (UnsupportedEncodingException e) {  
  32.             throw new RuntimeException(e);  
  33.         } catch (ParseException e) {  
  34.         } catch (IOException e) {  
  35.         }  
  36.   
  37.     }  
  38.   
  39. }  

2  對於實體的資源使用完之後要適當的回收資源,特別是對於流實體。例子代碼如下:

[java] view plaincopy
  1. public static void test() throws IllegalStateException, IOException{  
  2.         HttpResponse response = null;  
  3.         HttpEntity entity = response.getEntity();  
  4.   
  5.         if(entity!=null){  
  6.   
  7.                 InputStream is = entity.getContent();  
  8.                 try{  
  9.                     //做一些操作  
  10.                 }finally{  
  11.                     //最後別忘了關閉應該關閉的資源,適當的釋放資源  
  12.                     if(is != null){  
  13.                         is.close();  
  14.                     }  
  15.                     //這個方法也可以把底層的流給關閉了  
  16.                     EntityUtils.consume(entity);  
  17.                     //下面是這方法的源碼  
  18.                     /*public static void consume(final HttpEntity entity) throws IOException { 
  19.                         if (entity == null) { 
  20.                             return; 
  21.                         } 
  22.                         if (entity.isStreaming()) { 
  23.                             InputStream instream = entity.getContent(); 
  24.                             if (instream != null) { 
  25.                                 instream.close(); 
  26.                             } 
  27.                         } 
  28.                     }*/  
  29.                 }  
  30.   
  31.         }  
3
發佈了71 篇原創文章 · 獲贊 49 · 訪問量 49萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章