HttpEntity的使用

HttpEntity实体即可以使流也可以使字符串形式。

具体有什么用法看他的方法解释:

[html] view plain copy
  1. packagecom.scl.base;
  2. importjava.io.IOException;
  3. importjava.io.UnsupportedEncodingException;
  4. importorg.apache.http.HttpEntity;
  5. importorg.apache.http.ParseException;
  6. importorg.apache.http.entity.StringEntity;
  7. importorg.apache.http.util.EntityUtils;
  8. publicclassHttpClientDemo06{
  9. /**
  10. *@paramargs
  11. */
  12. publicstaticvoidmain(String[]args){
  13. try{
  14. HttpEntityentity=newStringEntity("这一个字符串实体","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(UnsupportedEncodingExceptione){
  28. thrownewRuntimeException(e);
  29. }catch(ParseExceptione){
  30. }catch(IOExceptione){
  31. }
  32. }
  33. }

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

[html] view plain copy
  1. publicstaticvoidtest()throwsIllegalStateException,IOException{
  2. HttpResponseresponse=null;
  3. HttpEntityentity=response.getEntity();
  4. if(entity!=null){
  5. InputStreamis=entity.getContent();
  6. try{
  7. //做一些操作
  8. }finally{
  9. //最后别忘了关闭应该关闭的资源,适当的释放资源
  10. if(is!=null){
  11. is.close();
  12. }
  13. //这个方法也可以把底层的流给关闭了
  14. EntityUtils.consume(entity);
  15. //下面是这方法的源码
  16. /*publicstaticvoidconsume(finalHttpEntityentity)throwsIOException{
  17. if(entity==null){
  18. return;
  19. }
  20. if(entity.isStreaming()){
  21. InputStreaminstream=entity.getContent();
  22. if(instream!=null){
  23. instream.close();
  24. }
  25. }
  26. }*/
  27. }
  28. }
转自:http://blog.csdn.net/com360/article/details/7645247
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值