HttpEntity的各种种类

本文主要介绍了HttpEntity在HTTP POST请求中的常见使用类型,包括BasicHttpEntity、StringEntity、UrlEncodedFormEntity、MultipartEntity,以及ByteArrayEntity、InputStreamEntity、FileEntity和BufferedHttpEntity等。这些类型在发送不同数据格式时各有用途。

HttpEntity我大多是用来做Httppost请求的
常用到的以下4种:BasicHttpEntity、StringEntity、UrlEncodedFormEntity、MultipartEntity

BasicHttpEntityDefaultHttpClient httpClient = new DefaultHttpClient();
param = "{json串}";
HttpPost httppost = new HttpPosturl);
BasicHttpEntity requestBody = new BasicHttpEntity();
requestBody.setContent(new ByteArrayInputStream(param.toString().getBytes("UTF-8")));
requestBody.setContentLength(param.toString().getBytes("UTF-8").length);
httppost.setEntity(requestBody);
HttpResponse httpResponse = httpClient.execute(httppost);

StringEntity
HttpPost httpPost = new HttpPost(url);  
StringEntity stringEntity = new StringEntity(param);//param参数,可以为"key1=value1&key2=value2"的一串字符串  
stringEntity.setContentType("application/x-www-form-urlencoded");  
httpPost.setEntity(stringEntity);  
HttpClient client = new DefaultHttpClient();   
HttpResponse httpResponse = client.execute(httpPost);  

UrlEncodedFormEntity
HttpPost httpPost = new HttpPost(url);  
List nvps = new ArrayList();  
nvps.add(new BasicNameValuePair("username", "vip"));  
nvps.add(new BasicNameValuePair("password", "secret"));  
httpPost.setEntity(new UrlEncodedFormEntity(nvps));  
httpclient.execute(httpPost);  

// 可以传文件的entity
MultipartEntity 
MultipartEntity entity = new MultipartEntity();
entity.addPart(“param1″, new StringBody(“李三”, Charset.forName(“UTF-8)));
entity.addPart(“param2″, new StringBody(“男”, Charset.forName(“UTF-8)));
entity.addPart(“param3″, new FileBody(new File(C:\\pic.gif”)));
HttpClient client = new DefaultHttpClient();
HttpPost postrequest = new HttpPost(url);
postrequest.setEntity(entity);
HttpResponse postresponse = client.execute(postrequest);

其次还有
ByteArrayEntity
InputreamEntity
FileEntity
BufferedHttpEntity
没有研究过,先记录在此。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值