HttpEntity的使用 .
2014-03-03 15:59
302 查看
HttpEntity实体即可以使流也可以使字符串形式。
具体有什么用法看他的方法解释:
对于实体的资源使用完之后要适当的回收资源,特别是对于流实体:例子代码如下
文章转自:/article/7963511.html
具体有什么用法看他的方法解释:
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) { } } }
对于实体的资源使用完之后要适当的回收资源,特别是对于流实体:例子代码如下
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(); } } }*/ } }
文章转自:/article/7963511.html
相关文章推荐
- HttpEntity的类型及其使用
- (原)使用TortoiseGit提交代码push的时候报错:HTTP 413 curl 22 The requested URL returned error: 413 Request Entity Too Large
- HttpEntity的使用
- 06_HttpEntity的使用
- HttpEntity的使用
- HttpEntity的类型及其使用
- HttpEntity的类型及其使用
- HttpClient使用详解(MultipartEntityBuilder 上传文件等)
- 06_HttpEntity的使用
- HttpClient使用MultipartEntityBuilder实现多文件上传
- 使用httpClient MultipartRequestEntity文件上传解析文件和普通表单参数
- HttpEntity的使用
- 关于使用Git的时候出现"HTTP 413 curl 22 The requested URL returned error: 413 Request Entity Too Large"的解决方法
- HttpEntity的类型及其使用
- HttpEntity的使用
- HttpReceiveRequestEntityBody 使用应注意的地方
- HttpClient 4.3.6 使用MultipartEntityBuilder实现类似form表单提交方式的文件上传
- HttpEntity的类型及其使用
- HttpURLConnection的使用
- 使用Java原生API编写发送HTTP_POST请求的工具类