HttpClient之EntityUtils对象

最近在学习安卓并用thinkphp做后台,为了抵抗自己的烂记性,就在这里记录一下当我从tp后台获取到json串传到安卓客户端所用到的一个方法函数。

EntityUtils对象是org.apache.http.util下的一个工具类,用官方的解释是为HttpEntity对象提供的静态帮助类,其常用的几个方法如下:

consume()方法;

consumeQuietly(HttpEntity)方法

toByteArray(final HttpEntity entity)方法

最主要的就是consume()这个方法,其功能就是关闭HttpEntity是的流,如果手动关闭了InputStream instream = entity.getContent();这个流,也可以不调用这个方法。看看了其源码就知道了:

而我在项目中用到的是

String data = EntityUtils.toString(response.getEntity());

我会在下一篇文章中把tp和安卓客户端的数据交互代码粘出来

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 {

HttpEntityentity=newStringEntity("这一个字符串实体", "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) {

}

}

}

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

public static void test() throws IllegalStateException, IOException{

HttpResponseresponse=null;

HttpEntityentity=response.getEntity();

if(entity!=null){

InputStreamis=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()) {

InputStreaminstream=entity.getContent();

if (instream != null) {

instream.close();

}

}

}*/

}

}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,785评论 18 399
  • http://blog.csdn.net/fengzheku/article/details/48447791 p...
    木子Qing阅读 2,584评论 1 1
  • 一. Java基础部分.................................................
    wy_sure阅读 3,845评论 0 11
  • 该文仅对于中间这种支付方式有参考价值哟 一、开发背景 在微信公众号中,需要进行微信支付且为微信公众号网页支付。 二...
    英文名叫夏天阅读 1,897评论 0 7
  • 这部分主要是开源Java EE框架方面的内容,包括Hibernate、MyBatis、Spring、Spring ...
    杂货铺老板阅读 1,448评论 0 2