Android实现Http协议案例

本文介绍了在Android开发中如何使用HTTP协议进行网络通信。包括GET和POST两种请求方式的具体实现过程,从创建请求到处理响应的完整流程。

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

在Android开发中,使用Http协议实现网络之间的通信是随处可见的,使用http方式主要采用2中请求方式即get和post两种方式。

一、使用get方式:

HttpGet httpGet = new HttpGet(url);
            // 生成一个客户端对象
            httpClient = new DefaultHttpClient();

            try {
                // 通过客户端对象httpClient的execute方法执行请求
                httpResponse = httpClient.execute(httpGet);
                httpEntity = httpResponse.getEntity();
                inputStream = httpEntity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String result = "";
                String line = "";
                while ((line = reader.readLine()) != null) {
                    result = result + line;
                }
                System.out.println(result);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

二、使用Post方式:

NameValuePair nameValuePair1 = new BasicNameValuePair("name", name);
            NameValuePair nameValuePair2 = new BasicNameValuePair("age", age);

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(nameValuePair1);
            nameValuePairs.add(nameValuePair2);
            try {
                httpEntity = new UrlEncodedFormEntity(nameValuePairs);
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(httpEntity);
                httpClient = new DefaultHttpClient();

                try {
                    httpResponse = httpClient.execute(httpPost);
                    httpEntity = httpResponse.getEntity();
                    inputStream = httpEntity.getContent();
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(inputStream));

                    String result = "";
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        result = result + line;

                    }
                    System.out.println(result);

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            break;
        }

 

转载于:https://www.cnblogs.com/yshuaiw/p/3433566.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值