您的位置:首页 > 理论基础 > 计算机网络

Android: 网络编程之Post传递参数

2012-03-19 11:02 309 查看
原文链接:http://blog.csdn.net/firewings_r/article/details/5374851

Android采用Post方式向服务器传递参数的步骤:

A、使用Map来存储参数

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

B、使用DefaultHttpClient创建HttpClient实例

DefaultHttpClient httpClient = new DefaultHttpClient();


C、构建HttpPost

HttpPost post = new HttpPost(“http://www.ataaw.com/..”);


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数据传递过程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: