首页 > 代码库 > android使用apache httpclient发送post请求
android使用apache httpclient发送post请求
package com.liuc; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; public class HttpPostUtil { public static String sendHttpPost(Map<String, String> map,String encode,String path){ List<NameValuePair> list=new ArrayList<NameValuePair>(); if (map!=null&&!map.isEmpty()) { for(Map.Entry<String, String> entry:map.entrySet()){ list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } try { //实现将参数封装到表单中,也就是请求体重 UrlEncodedFormEntity entity=new UrlEncodedFormEntity(list,encode); //使用post方式提交数据 HttpPost httpPost=new HttpPost(path); httpPost.setEntity(entity); RequestConfig requestConfig = RequestConfig.custom(). setSocketTimeout(2000).setConnectTimeout(2000).build();//4.3之后的设置请求和传输超时时间 httpPost.setConfig(requestConfig); //执行post请求 //3.X是这样的 //HttpClient httpClient=new DefaultHttpClient(); //4.x是这样的 HttpClient httpClient = HttpClients.createDefault(); HttpResponse httpResponse=httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode()==200) { return getStringForInputStream(httpResponse.getEntity().getContent(),encode); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return path; } private static String getStringForInputStream(InputStream inputStream, String encode) { ByteArrayOutputStream stream=new ByteArrayOutputStream(); byte[] data=http://www.mamicode.com/new byte[1024];>对于各个版本写法的区别。可以参考:http://www.open-open.com/lib/view/open1383751765321.html
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。