HttpEntity的类型及其使用

一 HttpEntity的类型

 

1  BasicHttpEntity

      代表底层流的基本实体。通常是在http报文中获取的实体。他只有一个空参的构造方法。刚创建时没有内容,长度为负值。需要通过两个方法,把值赋进去。

[java]  view plain  copy
  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 plain  copy
  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 plain  copy
  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 plain  copy
  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 plain  copy
  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 plain  copy
  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 plain  copy
  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 plain  copy
  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 plain  copy
  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 plain  copy
  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.         }  


 

FROM: http://blog.csdn.net/athenamax/article/details/8185043http://blog.csdn.net/athenamax/article/details/8185041

原文字体太小,看着眼睛疼,特此加大字体转载

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring MVC提供了一个HttpEntity类,用于封装HTTP请求和响应的实体。 HttpEntity是一个泛型类,可以用于封装各种类型的请求和响应体。它包含了HTTP头信息以及请求/响应的主体内容。 在Spring MVC中,我们可以将参数类型声明为HttpEntity,来接收和处理HTTP请求的实体信息。例如,我们可以将请求体中的JSON数据映射到一个Java对象中: ```java @RequestMapping(value = "/user", method = RequestMethod.POST) public ResponseEntity<String> createUser(@RequestBody HttpEntity<User> requestEntity) { User user = requestEntity.getBody(); // 处理user对象 // ... return new ResponseEntity<>("User created", HttpStatus.CREATED); } ``` 在上述例子中,我们使用了`HttpEntity<User>`作为参数类型来接收请求体中的JSON数据,并将其映射到一个User对象中。我们可以通过调用`getBody()`方法来获取请求体内容。 同样地,我们也可以在响应中使用HttpEntity来封装响应的内容。例如,我们可以返回一个包含JSON数据的HttpEntity对象: ```java @RequestMapping(value = "/user/{id}", method = RequestMethod.GET) public HttpEntity<User> getUser(@PathVariable("id") int id) { User user = userService.getUserById(id); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<>(user, headers); } ``` 在上述例子中,我们使用了`HttpEntity<User>`作为返回类型,并将User对象及自定义的HTTP头信息封装在其中。 总结而言,Spring MVC的HttpEntity类提供了一种方便的方式来封装和处理HTTP请求和响应的实体信息。我们可以使用它来接收和处理请求体中的内容,并将响应数据封装成一个HttpEntity对象返回给客户端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值