HttpEntity类的相关知识点(MultipartEntity)

代码转自http://blog.csdn.net/com360/article/details/7645247


这是一个Http请求的封装类,我们通过这个发送数据,也是通过这个接收数据,在进行处理

例如:

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"); //获取到一个HttpEntity的方式有很多,主要还是从respone中出来
			//内容类型
			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();
				            }
				        }
				    }*/
				}
				
			 
		}

更为详细的HttpEntity操作详见http://blog.csdn.net/com360/article/details/7645851

 MultipartEntity为一个可以上传文件的包装类

具体用法如下

MultipartEntity mpEntity = new MultipartEntity();
StringBody stringBody = new StringBody(value); //所有要传的数据全部改为Body类型
FileBody file = new FileBody(imageFile,"image/jpeg"); //所有要传的数据全部改为Body类型
mpEntity.addPart(key, stringBody);
mpEntity.addPart("pic", file);
httppost.setEntity(mpEntity);


UrlEncodedFormEntity这个类是用来把输入数据编码成合适的内容,比如

request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); //就是讲内容编译为 UTF-8的格式


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值