当前位置:   article > 正文

HttpEntity的类型及其使用_basichttpentity

basichttpentity

 

一 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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/302848
推荐阅读
相关标签
  

闽ICP备14008679号