Android网络编程之通过Post传递参数

本文详细介绍了在Android应用中使用Post方法进行客户端与服务端通讯的过程,包括使用Map存储参数、创建HttpClient实例、构建HttpPost、参数转换、设置Post实体以及执行Post方法等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A、使用Map来存储参数

Map<String, String> map = new HashMap<String, String>();
map.put("name", "onmoso");
map.put("password", "onmoso.com");

B、使用DefaultHttpClient创建HttpClient实例

DefaultHttpClient httpClient = new DefaultHttpClient();

C、构建HttpPost

HttpPost post = new HttpPost(“ http://www.onmoso.com/test.jsp ”);

D、将由Map存储的参数转化为键值NameValue

List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        postData.add(new BasicNameValuePair(entry.getKey(),
                                entry.getValue()));
                    }

E、使用编码构建Post实体

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                            postData, HTTP.UTF_8);

F、设置Post实体

post.setEntity(entity);

G、执行Post方法

HttpResponse response = httpClient.execute(post);

H、获取返回实体

HttpEntity httpEntity = response.getEntity();

I、将H中返回实体转化为输入流

InputStream is = httpEntity.getContent();

J、读取输入流

StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
           String line = "";
           while((line=br.readLine())!=null){
                    sb.append(line);
           }

以上就是Android中通过Post来实现客户端与服务端的通讯过程,完成参数封装到发送到服务器,最后接收服务端返回的数据,从而完成一个完整的HTTP数据传递过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值