`

HttpEntity类型有哪些

    博客分类:
  • Java
 
阅读更多

BasicHttpEntity

 

 代表底层流的基本实体。通常是在http报文中获取的实体。他只有一个空参的构造方法。

刚创建时没有内容,长度为负值。需要通过两个方法,把值赋进去。

 

[html] 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.     }  



 

ByteArrayEntity

 是自我包含的,可重复获得使用的,从指定的字节数组中取出内容的实体。

字节数组是这个实体的构造方法的参数

 

[html] 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.     }  



 

StringEntity

是自我包含的可重复的实体。通过String创建的实体

有两个构造方法,一个是自Sring为参数的构造方法,一个是以String和字符编码为参数的构造方法。

 

[html] 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.     }  



 

InputreamEntity

是流式不可以重复的实体。构造方法是InputStream 和内容长度,内容长度是输入流的长度

 

[html] 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.     }  



 

FileEntity

自我包含式,可以重复的实体。参数传入文件和文件类型。

 

 

[html] 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.     }  



 

EntityTemplete

从ContentProducer接口接受内容的实体。

在ContentProducer的实现类中写入想要写入的内容。

 

[html] 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.     }  



 

 

HttpEntityWrapper

这个是创建被包装实体的基类,有被包装实体的引用。

相当于实体的代理类,被包装实体是他的一个属性。

下面是这个类的源码:

 

[html] 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. }  



 

BufferedHttpEntity

是HttpEntityWarpper的子类,可以把不可以重复的实体,实现成可以重复的实体。

它从提供的实体中读取内容,缓存到内容中。

源码如下:

 

[html] 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  
分享到:
评论

相关推荐

    springMVC-HttpEntity(ResponseEntity)demo

    在Spring MVC框架中,HttpEntity和ResponseEntity是两个非常重要的概念,它们主要用于处理HTTP请求和响应。本项目“springMVC-HttpEntity(ResponseEntity)demo”是一个实战演示,展示了如何在Spring MVC应用中使用...

    org.apache.http.entity.mime

    HttpEntity entity = builder.build(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entity); ``` 这个例子中,`addTextBody`和`addBinaryBody`分别用于添加文本和二进制数据,`ContentType.create...

    org.apache.http.entity.mime和org.apache.http.legacy

    在提供的信息中,我们关注的是两个特定的模块:"org.apache.http.entity.mime" 和 "org.apache.http.legacy"。 首先,`org.apache.http.entity.mime` 是 Apache HttpClient 库的一个子模块,专门用于处理MIME(多...

    httpmime-4.1.2.jar org.apache.http.entity.mime

    它提供了丰富的API来创建、解析和处理MIME类型的HTTP请求和响应。在Android开发中,HttpMime 4.1.2.jar是一个重要的依赖库,它帮助开发者高效地处理HTTP通信中的多媒体数据,如图片、音频、视频等。 1. **HttpMime...

    org.apache.http jar包下载

    - `HttpEntity`:表示HTTP消息中的实体,可以是请求体或响应体。 - `EntityUtils`:提供了一些实用方法,如读取实体内容、关闭实体等。 在使用Apache HTTP客户端库时,你需要先创建`HttpClient`实例,然后构造`...

    httpmime jar包

    import org.apache.http.HttpEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; // 创建MultipartEntityBuilder ...

    WCF WebHttp REST Entity Service

    **WCF WebHttp REST Entity Service** 是一个基于Windows Communication Foundation (WCF) 技术的Web服务实现,它专门设计用于构建RESTful风格的应用程序。REST(Representational State Transfer)是一种架构风格,...

    org.apache.http 依赖包

    3. **HttpEntity**:表示HTTP消息实体,可以是请求或响应中的数据。它可以是文本、二进制数据或流。 4. **BasicNameValuePair和NameValuePair**:用于构建HTTP请求参数,常见于POST请求的表单数据。 5. **...

    asp.net+wcf+entity framework

    WCF服务可以通过配置文件定义其行为,包括端点地址、绑定类型和合同类型,这些服务可以被其他应用程序通过网络调用。 **Entity Framework** Entity Framework是一个对象关系映射(ORM)框架,它简化了.NET开发者与...

    EasyUI框架(ajax for WCF和Entity FrameWork4.1)

    WCF是.NET框架的一个重要组成部分,它提供了一种统一的服务模型,可以创建各种类型的分布式应用程序。通过WCF,开发者能够构建高度可配置、跨平台的服务,这些服务可以通过多种传输协议(如HTTP、TCP)进行通信。 ...

    org.apache.HTTP需要的jar包

    此包中的主要类包括`CloseableHttpClient`(负责创建和管理HTTP客户端实例)、`HttpGet`、`HttpPost`(用于构造不同类型的HTTP请求)和`CloseableHttpResponse`(用于接收和处理HTTP响应)。 `httpcomponents-core-...

    httpmime.jar

    2. 处理MIME类型的HTTP响应:库中的HttpEntity类及其子类,如BasicHttpEntity和FileEntity,用于处理HTTP响应中的实体内容。这些实体可以是简单的文本,也可以是复杂的MIME多部分数据,如附件下载。 3. 文件上传与...

    http、restTemplate请求资源(含带头部信息)

    HttpEntity&lt;Map, String&gt;&gt; entity = new HttpEntity&lt;&gt;(requestBody, headers); ResponseEntity&lt;String&gt; response = restTemplate.exchange( "http://example.com/api/resource", HttpMethod.POST, entity, String....

    SpringMVC源码总结(九)HandlerMethodArgumentResolver介绍.pdf

    - `HttpEntityMethodProcessor`:处理`HttpEntity`类型的参数,无论是在请求还是响应中。`HttpEntity`代表了一个HTTP消息实体,可以包含头信息和主体。 - `RequestResponseBodyMethodProcessor`:支持`@Request...

    使用spring restTemplete 调用腾讯接口返回Entity

    HttpEntity&lt;String&gt; entity = new HttpEntity&lt;&gt;(requestBody, headers); // 设置请求头 ResponseEntity&lt;MyResponse&gt; response = restTemplate.postForEntity(url, entity, MyResponse.class); // 发送请求并转换为...

    MultipartEntityBuilder使用jar包

    5. **构建并获取`HttpEntity`对象**: ```java HttpEntity entity = builder.build(); ``` 6. **创建`HttpPost`请求**: ```java HttpPost httpPost = new HttpPost("http://your/upload/url"); ...

    ASP.NET MVC with Entity Framework and CSS pdf图书+源代码

    3. **控制器**:介绍如何创建控制器,处理HTTP请求,并返回视图或JSON等不同类型的响应。 4. **视图**:讲解视图的创建和渲染,以及如何使用razor语法来动态生成HTML。 5. **模型绑定**:说明如何将HTTP请求数据自动...

    httpmime-4.25.jar.zip

    4. `HttpEntity`:代表HTTP消息体,包含了所有可能的HTTP内容类型。 四、使用示例 以下是一个简单的使用httpmime-4.25.jar发送POST请求并上传文件的Java代码示例: ```java CloseableHttpClient httpClient = ...

    httpclient发送get请求和post请求demo

    import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; ...

    RestTemplate如何通过HTTP Basic Auth认证.docx

    4. 使用 RestTemplate 的 exchange 方法,指定 URL、HTTP 方法、HttpEntity 和期望的响应类型。 以下是一个示例代码片段,展示了如何使用 RestTemplate 进行 HTTP Basic Auth: ```java @RestController @...

Global site tag (gtag.js) - Google Analytics