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

                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数据传递过程。           

猜你喜欢

转载自blog.csdn.net/qq_44919253/article/details/89353991
今日推荐