HttpEntity实体即可以使流也可以使字符串形式。
具体有什么用法看他的方法解释:
- packagecom.scl.base;
- importjava.io.IOException;
- importjava.io.UnsupportedEncodingException;
- importorg.apache.http.HttpEntity;
- importorg.apache.http.ParseException;
- importorg.apache.http.entity.StringEntity;
- importorg.apache.http.util.EntityUtils;
- publicclassHttpClientDemo06{
- /**
- *@paramargs
- */
- publicstaticvoidmain(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(UnsupportedEncodingExceptione){
- thrownewRuntimeException(e);
- }catch(ParseExceptione){
- }catch(IOExceptione){
- }
- }
- }
对于实体的资源使用完之后要适当的回收资源,特别是对于流实体:例子代码如下
- publicstaticvoidtest()throwsIllegalStateException,IOException{
- HttpResponseresponse=null;
- HttpEntityentity=response.getEntity();
- if(entity!=null){
- InputStreamis=entity.getContent();
- try{
- //做一些操作
- }finally{
- //最后别忘了关闭应该关闭的资源,适当的释放资源
- if(is!=null){
- is.close();
- }
- //这个方法也可以把底层的流给关闭了
- EntityUtils.consume(entity);
- //下面是这方法的源码
- /*publicstaticvoidconsume(finalHttpEntityentity)throwsIOException{
- if(entity==null){
- return;
- }
- if(entity.isStreaming()){
- InputStreaminstream=entity.getContent();
- if(instream!=null){
- instream.close();
- }
- }
- }*/
- }
- }