前面一篇文章《Android网络编程之通过Get方法实现》我们讲解了Android中通过Get方法实现网络编程的基本例子,我们知道,在网络编程中还有另一个方法,就是通过Psot来实现与服务器的数据交换,因此在本文中将对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数据传递过程。