android 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 map,String encode,String path){

List list=new ArrayList();

if (map!=null&&!map.isEmpty()) {

for(Map.Entry 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=new byte[1024];

int len=0;

String result="";

try {

if (inputStream != null) {

while ((len = inputStream.read(data)) != -1) {

stream.write(data, 0, len);

}

result=new String(stream.toByteArray(),encode);

}

} catch (Exception e) {

}

return result;

}

}

对于各个版本写法的区别。可以参考:http://www.open-open.com/lib/view/open1383751765321.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值