HttpEntity的类型及其使用
一 HttpEntity的类型
1 BasicHttpEntity
代表底层流的基本实体。通常是在http报文中获取的实体。他只有一个空参的构造方法。刚创建时没有内容,长度为负值。需要通过两个方法,把值赋进去。
/**
* BasicHttpEntity
* @throws IOException
*/
public static void testBasicHttpEntity() throws IOException{
InputStream is = null;
//BasicHttpEntity这类就是一个输入流的内容包装类,包装内容的相关的编码格式,长度等
BasicHttpEntity entity = new BasicHttpEntity();
//设置内容
entity.setContent(is);
//设置长度
entity.setContentLength(is.available());
//没搞懂chunked这个属性啥意思
entity.setChunked(false);
}
2 ByteArrayEntity
是自我包含的,可重复获得使用的,从指定的字节数组中取出内容的实体。字节数组是这个实体的构造方法的参数。
/**
* ByteArrayEntity
* @throws IOException
*/
public static void testByteArrayEntity() throws IOException{
ByteArrayEntity entity = new ByteArrayEntity("内容".getBytes());
ByteArrayInputStream is = (ByteArrayInputStream) entity.getContent();
//上面这行代码返回的其实是一个ByteArrayInputStream对象
/*public InputStream getContent() {
return new ByteArrayInputStream(this.b, this.off, this.len);
}*/
}
3 StringEntity
是自我包含的可重复的实体。通过String创建的实体。有两个构造方法,一个是自Sring为参数的构造方法,一个是以String和字符编码为参数的构造方法。
/**
* StringEntity
* @throws IOException
*/
public static void testStringEntity() throws IOException{
StringBuilder sb = new StringBuilder();
//获取系统的信息集合,这个集合是不可以修改的
Map<String, String> nev = System.getenv();
for(Entry<String, String> entry : nev.entrySet()){
sb.append(entry.getKey()).append("=")
.append(entry.getValue()).append("\n");
}
String content = sb.toString();
System.out.println(content);
//创建只带字符串参数的
StringEntity entity = new StringEntity(content);
//创建带字符创参数和字符编码的
StringEntity entity2 = new StringEntity(content, "UTF-8");
}
4 InputreamEntity
是流式不可以重复的实体。构造方法是InputStream 和内容长度,内容长度是输入流的长度。
/**
* InputStreamEntity
* @throws IOException
*/
public static void testInputStreamEntity() throws IOException{
InputStream is = null;
//InputStreamEntity严格是对内容和长度相匹配的。用法和BasicHttpEntity类似
InputStreamEntity entity = new InputStreamEntity(is, is.available());
}
5 FileEntity
自我包含式,可以重复的实体。参数传入文件和文件类型。
/**
* FileEntity
* @throws IOException
*/
public static void testFileEntity() throws IOException{
FileEntity entity = new FileEntity(new File(""), ContentType.APPLICATION_FORM_URLENCODED);
FileEntity entity2 = new FileEntity(new File(""), "application/java-achive");
}
6 EntityTemplete
从ContentProducer接口接受内容的实体。在ContentProducer的实现类中写入想要写入的内容。
/**
* EntityTemplate
* @throws IOException
*/
public static void testEntityTemplate() throws IOException{
ContentProducer producer = new ContentProducer() {
@Override
public void writeTo(OutputStream outstream) throws IOException {
outstream.write("这是什么东东》。".getBytes());
}
};
EntityTemplate entity = new EntityTemplate(producer);
entity.writeTo(System.out);
}
7 HttpEntityWrapper
这个是创建被包装实体的基类,有被包装实体的引用。相当于实体的代理类,被包装实体是他的一个属性。下面是这个类的源码:
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.entity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.annotation.NotThreadSafe;
/**
* Base class for wrapping entities.
* Keeps a {@link #wrappedEntity wrappedEntity} and delegates all
* calls to it. Implementations of wrapping entities can derive
* from this class and need to override only those methods that
* should not be delegated to the wrapped entity.
*
* @since 4.0
*/
@NotThreadSafe
public class HttpEntityWrapper implements HttpEntity {
/** The wrapped entity. */
protected HttpEntity wrappedEntity;
/**
* Creates a new entity wrapper.
*
* @param wrapped the entity to wrap, not null
* @throws IllegalArgumentException if wrapped is null
*/
public HttpEntityWrapper(HttpEntity wrapped) {
super();
if (wrapped == null) {
throw new IllegalArgumentException
("wrapped entity must not be null");
}
wrappedEntity = wrapped;
} // constructor
public boolean isRepeatable() {
return wrappedEntity.isRepeatable();
}
public boolean isChunked() {
return wrappedEntity.isChunked();
}
public long getContentLength() {
return wrappedEntity.getContentLength();
}
public Header getContentType() {
return wrappedEntity.getContentType();
}
public Header getContentEncoding() {
return wrappedEntity.getContentEncoding();
}
public InputStream getContent()
throws IOException {
return wrappedEntity.getContent();
}
public void writeTo(OutputStream outstream)
throws IOException {
wrappedEntity.writeTo(outstream);
}
public boolean isStreaming() {
return wrappedEntity.isStreaming();
}
/**
* @deprecated (4.1) Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that;
* otherwise call {@link #writeTo(OutputStream)} which is required to free the resources.
*/
@Deprecated
public void consumeContent() throws IOException {
wrappedEntity.consumeContent();
}
}
8 BufferedHttpEntity
是HttpEntityWarpper的子类,可以把不可以重复的实体,实现成可以重复的实体。它从提供的实体中读取内容,缓存到内容中。源码如下:
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.entity;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.util.EntityUtils;
/**
* A wrapping entity that buffers it content if necessary.
* The buffered entity is always repeatable.
* If the wrapped entity is repeatable itself, calls are passed through.
* If the wrapped entity is not repeatable, the content is read into a
* buffer once and provided from there as often as required.
*
* @since 4.0
*/
@NotThreadSafe
public class BufferedHttpEntity extends HttpEntityWrapper {
private final byte[] buffer;
/**
* Creates a new buffered entity wrapper.
*
* @param entity the entity to wrap, not null
* @throws IllegalArgumentException if wrapped is null
*/
public BufferedHttpEntity(final HttpEntity entity) throws IOException {
super(entity);
if (!entity.isRepeatable() || entity.getContentLength() < 0) {
this.buffer = EntityUtils.toByteArray(entity);
} else {
this.buffer = null;
}
}
@Override
public long getContentLength() {
if (this.buffer != null) {
return this.buffer.length;
} else {
return wrappedEntity.getContentLength();
}
}
@Override
public InputStream getContent() throws IOException {
if (this.buffer != null) {
return new ByteArrayInputStream(this.buffer);
} else {
return wrappedEntity.getContent();
}
}
/**
* Tells that this entity does not have to be chunked.
*
* @return <code>false</code>
*/
@Override
public boolean isChunked() {
return (buffer == null) && wrappedEntity.isChunked();
}
/**
* Tells that this entity is repeatable.
*
* @return <code>true</code>
*/
@Override
public boolean isRepeatable() {
return true;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
if (outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
if (this.buffer != null) {
outstream.write(this.buffer);
} else {
wrappedEntity.writeTo(outstream);
}
}
// non-javadoc, see interface HttpEntity
@Override
public boolean isStreaming() {
return (buffer == null) && wrappedEntity.isStreaming();
}
} // class BufferedHttpEntity
二 HttpEntity 的使用
1 HttpEntity实体即可以使流也可以使字符串形式。具体有什么用法看他的方法解释:
package com.scl.base;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
public class HttpClientDemo06 {
/**
* @param args
*/
public static void main(String[] args) {
try {
HttpEntity entity = new StringEntity("这一个字符串实体", "UTF-8");
//内容类型
System.out.println(entity.getContentType());
//内容的编码格式
System.out.println(entity.getContentEncoding());
//内容的长度
System.out.println(entity.getContentLength());
//把内容转成字符串
System.out.println(EntityUtils.toString(entity));
//内容转成字节数组
System.out.println(EntityUtils.toByteArray(entity).length);
//还有个直接获得流
//entity.getContent();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (ParseException e) {
} catch (IOException e) {
}
}
}
2 对于实体的资源使用完之后要适当的回收资源,特别是对于流实体。例子代码如下:
public static void test() throws IllegalStateException, IOException{
HttpResponse response = null;
HttpEntity entity = response.getEntity();
if(entity!=null){
InputStream is = entity.getContent();
try{
//做一些操作
}finally{
//最后别忘了关闭应该关闭的资源,适当的释放资源
if(is != null){
is.close();
}
//这个方法也可以把底层的流给关闭了
EntityUtils.consume(entity);
//下面是这方法的源码
/*public static void consume(final HttpEntity entity) throws IOException {
if (entity == null) {
return;
}
if (entity.isStreaming()) {
InputStream instream = entity.getContent();
if (instream != null) {
instream.close();
}
}
}*/
}
}
FROM: http://blog.csdn.net/athenamax/article/details/8185043http://blog.csdn.net/athenamax/article/details/8185041
原文字体太小,看着眼睛疼,特此加大字体转载
HttpEntity的类型及其使用相关推荐
- org.springframework.web.client.HttpServerErrorException
错误场景:lz在使用restTemplete发起post请求时,由于对HttpEntity参数类型不太了解,报此异常. 使用post请求,当contentType为application/json时: ...
- SpringMVC对HTTP报文体的处理
客户端和服务端HTTP报文传递消息,而HTTP报文包含报文头和报文体.通常,解析请求参数以及返回页面都不需要我们关心HTTP报文体的读取和生成过程.但在某些特定场景下需要直接到请求报文中读取报文体,或 ...
- 《疯狂Java讲义》(第5版) 作者李刚(待重新排版)
第1章 Java语言概述与开发环境 1.1 Java语言的发展简史 JDK1.0 : Sun在1996年年初发布了JDK 1.0,该版本包括两部分:运行环境(即JRE)和开发环境(即JDK).运行环境 ...
- Spring MVC 解决日期类型动态绑定问题
出处:http://www.cnblogs.com/crazy-fox/archive/2012/02/18/2357699.html ean 名为User,则在相同的包中存在UserEditor类可 ...
- java调接口传值_关于调用第三方接口时传递参数是File类型的解决方式
正版编程与类型系统讲解基于的应用 77.35元 (需用券) 去购买 > 最近项目,需要我调用另一个项目中的某个接口,接口的入参为File类型,要拿到此接口返回的数据@ApiOperation(& ...
- #{}不自动改参数类型_Spring参数的自解析还在自己转换?你out了!
背景前段时间开发一个接口,因为调用我接口的同事脾气特别好,我也就不客气,我就直接把源代码发给他当接口定义了. 没想到同事看到我的代码问:要么 get a,b,c 要么 post [a,b,c]. ...
- 如何判断Map中的key或value是什么类型
对于某些从泛型(比如:Map<K, V>)中继承过来的数据,K可能是String.Integer.等等.如果需要map.get(key),得先确保key的类型跟map的K匹配. 对于key ...
- SpringMVC——对Ajax的处理(包含 JSON 类型)
一.首先要搞明白的一些事情. 1.从客户端来看,需要搞明白: (1)要发送什么样格式的 JSON 数据才能被服务器端的 SpringMVC 很便捷的处理,怎么才能让我们写更少的代码,如何做好 JSON ...
- Java企业微信开发-企业微信所有类型消息推送封装
企业微信开发第一步获取AccessToken,企业微信的AccessToken和公众号的不一样,企业微信所有接口调用只需要一个AccessToken,而公众号授权和jssdk是分开的 一.获取企业微信 ...
最新文章
- html表单的创建和css的构成
- 我的商汤实习年末总结
- 【数据迁移】使用传输表空间迁移数据
- 【WebRTC---入门篇】(九)WebRTC网络基础:P2P/STUN/TURN/ICE
- Hyhyhy – 专业的 HTML5 演示文稿工具
- 客户端程序自动更新(升级)的方式
- 简单的故事品味生活,
- C++编程语言中引用(reference)介绍
- 在线Excel的前端组件、控件,实现web Excel
- Ubuntu 安装绿联CM448无线网卡驱动
- 台式电脑主板插线步骤图_电脑主板跳线接法图文教程(安装过程)
- Java高铁的速度是火车的两倍_超级高铁最高速度是飞机速度的近两倍,如果研发成功,对中国房价涨跌和中国高铁的比较优势会有什么影响?...
- 健康体检信息系统源码、医院体检源码 医院管理系统源码
- IOS ipv6测试
- 理解什么叫“自然拼读”
- 智慧商圈,对接微信、支付宝、云闪付实现自动积分
- C# Bitmap GetPixel 效率太低,太慢的替代方法
- Android兼容8.0后APP图标变为原生小机器人图标
- AD布线布局和抗干扰
- ffmpeg sws_scale详细分析
热门文章
- 小明有N(4≤N≤60)个玻璃球,他想将N个玻璃球拆分成若干份(份数≥2,且每份中的数量互不相等),从而使拆分后的每份玻璃球数量的乘积最大。请你编写程序帮助小明计算出最大乘积是多少...
- git revert讲解
- 简易RTMP流媒体服务器搭建 一
- 某梆企业版加固脱壳及抽代码还原方法--dvmResolveClass
- php taint扩展,检测XSS漏洞的扩展 PHP Taint
- 高并发百万级热点key处理方案
- 用户时间争夺战打响,“弹幕”能否撑起微博的“短视频”梦?
- 现在,中国的互联网公司该不该走出国门?
- 远程服务器桌面不显示解决方法
- Goland常用快捷键设置