一 HttpEntity的类型

1  BasicHttpEntity

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

  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

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

  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和字符编码为参数的构造方法。

  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. }

4  InputreamEntity

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

  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

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

  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. }

6  EntityTemplete

从ContentProducer接口接受内容的实体。在ContentProducer的实现类中写入想要写入的内容。

  1. /**

  2. * EntityTemplate

  3. * @throws IOException

  4. */

  5. public static void testEntityTemplate() throws IOException{

  6. ContentProducer producer = new ContentProducer() {

  7. @Override

  8. public void writeTo(OutputStream outstream) throws IOException {

  9. outstream.write("这是什么东东》。".getBytes());

  10. }

  11. };

  12. EntityTemplate entity = new EntityTemplate(producer);

  13. entity.writeTo(System.out);

  14. }

7  HttpEntityWrapper

这个是创建被包装实体的基类,有被包装实体的引用。相当于实体的代理类,被包装实体是他的一个属性。下面是这个类的源码:

  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. package org.apache.http.entity;

  28. import java.io.IOException;

  29. import java.io.InputStream;

  30. import java.io.OutputStream;

  31. import org.apache.http.Header;

  32. import org.apache.http.HttpEntity;

  33. import org.apache.http.annotation.NotThreadSafe;

  34. /**

  35. * Base class for wrapping entities.

  36. * Keeps a {@link #wrappedEntity wrappedEntity} and delegates all

  37. * calls to it. Implementations of wrapping entities can derive

  38. * from this class and need to override only those methods that

  39. * should not be delegated to the wrapped entity.

  40. *

  41. * @since 4.0

  42. */

  43. @NotThreadSafe

  44. public class HttpEntityWrapper implements HttpEntity {

  45. /** The wrapped entity. */

  46. protected HttpEntity wrappedEntity;

  47. /**

  48. * Creates a new entity wrapper.

  49. *

  50. * @param wrapped the entity to wrap, not null

  51. * @throws IllegalArgumentException if wrapped is null

  52. */

  53. public HttpEntityWrapper(HttpEntity wrapped) {

  54. super();

  55. if (wrapped == null) {

  56. throw new IllegalArgumentException

  57. ("wrapped entity must not be null");

  58. }

  59. wrappedEntity = wrapped;

  60. } // constructor

  61. public boolean isRepeatable() {

  62. return wrappedEntity.isRepeatable();

  63. }

  64. public boolean isChunked() {

  65. return wrappedEntity.isChunked();

  66. }

  67. public long getContentLength() {

  68. return wrappedEntity.getContentLength();

  69. }

  70. public Header getContentType() {

  71. return wrappedEntity.getContentType();

  72. }

  73. public Header getContentEncoding() {

  74. return wrappedEntity.getContentEncoding();

  75. }

  76. public InputStream getContent()

  77. throws IOException {

  78. return wrappedEntity.getContent();

  79. }

  80. public void writeTo(OutputStream outstream)

  81. throws IOException {

  82. wrappedEntity.writeTo(outstream);

  83. }

  84. public boolean isStreaming() {

  85. return wrappedEntity.isStreaming();

  86. }

  87. /**

  88. * @deprecated (4.1) Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that;

  89. * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources.

  90. */

  91. @Deprecated

  92. public void consumeContent() throws IOException {

  93. wrappedEntity.consumeContent();

  94. }

  95. }

8  BufferedHttpEntity

是HttpEntityWarpper的子类,可以把不可以重复的实体,实现成可以重复的实体。它从提供的实体中读取内容,缓存到内容中。源码如下:

  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. package org.apache.http.entity;

  28. import java.io.ByteArrayInputStream;

  29. import java.io.IOException;

  30. import java.io.InputStream;

  31. import java.io.OutputStream;

  32. import org.apache.http.HttpEntity;

  33. import org.apache.http.annotation.NotThreadSafe;

  34. import org.apache.http.util.EntityUtils;

  35. /**

  36. * A wrapping entity that buffers it content if necessary.

  37. * The buffered entity is always repeatable.

  38. * If the wrapped entity is repeatable itself, calls are passed through.

  39. * If the wrapped entity is not repeatable, the content is read into a

  40. * buffer once and provided from there as often as required.

  41. *

  42. * @since 4.0

  43. */

  44. @NotThreadSafe

  45. public class BufferedHttpEntity extends HttpEntityWrapper {

  46. private final byte[] buffer;

  47. /**

  48. * Creates a new buffered entity wrapper.

  49. *

  50. * @param entity the entity to wrap, not null

  51. * @throws IllegalArgumentException if wrapped is null

  52. */

  53. public BufferedHttpEntity(final HttpEntity entity) throws IOException {

  54. super(entity);

  55. if (!entity.isRepeatable() || entity.getContentLength() < 0) {

  56. this.buffer = EntityUtils.toByteArray(entity);

  57. } else {

  58. this.buffer = null;

  59. }

  60. }

  61. @Override

  62. public long getContentLength() {

  63. if (this.buffer != null) {

  64. return this.buffer.length;

  65. } else {

  66. return wrappedEntity.getContentLength();

  67. }

  68. }

  69. @Override

  70. public InputStream getContent() throws IOException {

  71. if (this.buffer != null) {

  72. return new ByteArrayInputStream(this.buffer);

  73. } else {

  74. return wrappedEntity.getContent();

  75. }

  76. }

  77. /**

  78. * Tells that this entity does not have to be chunked.

  79. *

  80. * @return <code>false</code>

  81. */

  82. @Override

  83. public boolean isChunked() {

  84. return (buffer == null) && wrappedEntity.isChunked();

  85. }

  86. /**

  87. * Tells that this entity is repeatable.

  88. *

  89. * @return <code>true</code>

  90. */

  91. @Override

  92. public boolean isRepeatable() {

  93. return true;

  94. }

  95. @Override

  96. public void writeTo(final OutputStream outstream) throws IOException {

  97. if (outstream == null) {

  98. throw new IllegalArgumentException("Output stream may not be null");

  99. }

  100. if (this.buffer != null) {

  101. outstream.write(this.buffer);

  102. } else {

  103. wrappedEntity.writeTo(outstream);

  104. }

  105. }

  106. // non-javadoc, see interface HttpEntity

  107. @Override

  108. public boolean isStreaming() {

  109. return (buffer == null) && wrappedEntity.isStreaming();

  110. }

  111. } // class BufferedHttpEntity

二 HttpEntity 的使用

1  HttpEntity实体即可以使流也可以使字符串形式。具体有什么用法看他的方法解释:

  1. package com.scl.base;

  2. import java.io.IOException;

  3. import java.io.UnsupportedEncodingException;

  4. import org.apache.http.HttpEntity;

  5. import org.apache.http.ParseException;

  6. import org.apache.http.entity.StringEntity;

  7. import org.apache.http.util.EntityUtils;

  8. public class HttpClientDemo06 {

  9. /**

  10. * @param args

  11. */

  12. public static void main(String[] args) {

  13. try {

  14. HttpEntity entity = new StringEntity("这一个字符串实体", "UTF-8");

  15. //内容类型

  16. System.out.println(entity.getContentType());

  17. //内容的编码格式

  18. System.out.println(entity.getContentEncoding());

  19. //内容的长度

  20. System.out.println(entity.getContentLength());

  21. //把内容转成字符串

  22. System.out.println(EntityUtils.toString(entity));

  23. //内容转成字节数组

  24. System.out.println(EntityUtils.toByteArray(entity).length);

  25. //还有个直接获得流

  26. //entity.getContent();

  27. } catch (UnsupportedEncodingException e) {

  28. throw new RuntimeException(e);

  29. } catch (ParseException e) {

  30. } catch (IOException e) {

  31. }

  32. }

  33. }

2  对于实体的资源使用完之后要适当的回收资源,特别是对于流实体。例子代码如下:

  1. public static void test() throws IllegalStateException, IOException{

  2. HttpResponse response = null;

  3. HttpEntity entity = response.getEntity();

  4. if(entity!=null){

  5. InputStream is = entity.getContent();

  6. try{

  7. //做一些操作

  8. }finally{

  9. //最后别忘了关闭应该关闭的资源,适当的释放资源

  10. if(is != null){

  11. is.close();

  12. }

  13. //这个方法也可以把底层的流给关闭了

  14. EntityUtils.consume(entity);

  15. //下面是这方法的源码

  16. /*public static void consume(final HttpEntity entity) throws IOException {

  17. if (entity == null) {

  18. return;

  19. }

  20. if (entity.isStreaming()) {

  21. InputStream instream = entity.getContent();

  22. if (instream != null) {

  23. instream.close();

  24. }

  25. }

  26. }*/

  27. }

  28. }

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

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

HttpEntity的类型及其使用相关推荐

  1. org.springframework.web.client.HttpServerErrorException

    错误场景:lz在使用restTemplete发起post请求时,由于对HttpEntity参数类型不太了解,报此异常. 使用post请求,当contentType为application/json时: ...

  2. SpringMVC对HTTP报文体的处理

    客户端和服务端HTTP报文传递消息,而HTTP报文包含报文头和报文体.通常,解析请求参数以及返回页面都不需要我们关心HTTP报文体的读取和生成过程.但在某些特定场景下需要直接到请求报文中读取报文体,或 ...

  3. 《疯狂Java讲义》(第5版) 作者李刚(待重新排版)

    第1章 Java语言概述与开发环境 1.1 Java语言的发展简史 JDK1.0 : Sun在1996年年初发布了JDK 1.0,该版本包括两部分:运行环境(即JRE)和开发环境(即JDK).运行环境 ...

  4. Spring MVC 解决日期类型动态绑定问题

    出处:http://www.cnblogs.com/crazy-fox/archive/2012/02/18/2357699.html ean 名为User,则在相同的包中存在UserEditor类可 ...

  5. java调接口传值_关于调用第三方接口时传递参数是File类型的解决方式

    正版编程与类型系统讲解基于的应用 77.35元 (需用券) 去购买 > 最近项目,需要我调用另一个项目中的某个接口,接口的入参为File类型,要拿到此接口返回的数据@ApiOperation(& ...

  6. #{}不自动改参数类型_Spring参数的自解析还在自己转换?你out了!

    背景前段时间开发一个接口,因为调用我接口的同事脾气特别好,我也就不客气,我就直接把源代码发给他当接口定义了. 没想到同事看到我的代码问:要么 get  a,b,c  要么  post [a,b,c]. ...

  7. 如何判断Map中的key或value是什么类型

    对于某些从泛型(比如:Map<K, V>)中继承过来的数据,K可能是String.Integer.等等.如果需要map.get(key),得先确保key的类型跟map的K匹配. 对于key ...

  8. SpringMVC——对Ajax的处理(包含 JSON 类型)

    一.首先要搞明白的一些事情. 1.从客户端来看,需要搞明白: (1)要发送什么样格式的 JSON 数据才能被服务器端的 SpringMVC 很便捷的处理,怎么才能让我们写更少的代码,如何做好 JSON ...

  9. Java企业微信开发-企业微信所有类型消息推送封装

    企业微信开发第一步获取AccessToken,企业微信的AccessToken和公众号的不一样,企业微信所有接口调用只需要一个AccessToken,而公众号授权和jssdk是分开的 一.获取企业微信 ...

最新文章

  1. html表单的创建和css的构成
  2. 我的商汤实习年末总结
  3. 【数据迁移】使用传输表空间迁移数据
  4. 【WebRTC---入门篇】(九)WebRTC网络基础:P2P/STUN/TURN/ICE
  5. Hyhyhy – 专业的 HTML5 演示文稿工具
  6. 客户端程序自动更新(升级)的方式
  7. 简单的故事品味生活,
  8. C++编程语言中引用(reference)介绍
  9. 在线Excel的前端组件、控件,实现web Excel
  10. Ubuntu 安装绿联CM448无线网卡驱动
  11. 台式电脑主板插线步骤图_电脑主板跳线接法图文教程(安装过程)
  12. Java高铁的速度是火车的两倍_超级高铁最高速度是飞机速度的近两倍,如果研发成功,对中国房价涨跌和中国高铁的比较优势会有什么影响?...
  13. 健康体检信息系统源码、医院体检源码 医院管理系统源码
  14. IOS ipv6测试
  15. 理解什么叫“自然拼读”
  16. 智慧商圈,对接微信、支付宝、云闪付实现自动积分
  17. C# Bitmap GetPixel 效率太低,太慢的替代方法
  18. Android兼容8.0后APP图标变为原生小机器人图标
  19. AD布线布局和抗干扰
  20. ffmpeg sws_scale详细分析

热门文章

  1. 小明有N(4≤N≤60)个玻璃球,他想将N个玻璃球拆分成若干份(份数≥2,且每份中的数量互不相等),从而使拆分后的每份玻璃球数量的乘积最大。请你编写程序帮助小明计算出最大乘积是多少...
  2. git revert讲解
  3. 简易RTMP流媒体服务器搭建 一
  4. 某梆企业版加固脱壳及抽代码还原方法--dvmResolveClass
  5. php taint扩展,检测XSS漏洞的扩展 PHP Taint
  6. 高并发百万级热点key处理方案
  7. 用户时间争夺战打响,“弹幕”能否撑起微博的“短视频”梦?
  8. 现在,中国的互联网公司该不该走出国门?
  9. 远程服务器桌面不显示解决方法
  10. Goland常用快捷键设置