• 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();

    }

    }

    }*/

    }

    }




  • 相关阅读:
    Linux效劳器装机安全快速进阶指南(6)
    VLC 0.8.6b
    Mesk:简洁而朴实的音乐播放器
    OpenOffice.org最先支持微软docx等技俩
    Rawstudio-轻松转换 RAW 图片
    Transmission 0.70
    Openoffice3.0: 微软Office的解散者?
    AcetoneISO:Linux 下的“Daemon Tools”
    OpenOffice3将支撑PDF编纂及ac琐屑
    Linux的主动实行措施cron和crontab(1)
  • 原文地址:https://www.cnblogs.com/jtlgb/p/10083314.html
Copyright © 2020-2023  润新知