HttpEntity我大多是用来做Httppost请求的
常用到的以下4种:BasicHttpEntity、StringEntity、UrlEncodedFormEntity、MultipartEntity
BasicHttpEntity:
DefaultHttpClient 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
没有研究过,先记录在此。
本文主要介绍了HttpEntity在HTTP POST请求中的常见使用类型,包括BasicHttpEntity、StringEntity、UrlEncodedFormEntity、MultipartEntity,以及ByteArrayEntity、InputStreamEntity、FileEntity和BufferedHttpEntity等。这些类型在发送不同数据格式时各有用途。

3万+

被折叠的 条评论
为什么被折叠?



