Android学习之HttpURLConnection对象的使用

使用HttpURLConnection对象发送数据到服务器和从服务器读取数据

开始之前先引用官方原话:

Android 6.0 release removes support for the Apache HTTP client. If your app is using this client and targets Android 2.3 (API level 9) or higher, use the HttpURLConnection class instead. This API is more efficient because it reduces network use through transparent compression and response caching, and minimizes power consumption.

google官方从android6.0中移除了Apache HTTP Client API一定有他的道理,可能是比较耗电。

google官方推荐使用HttpURLConnection 来进行网络通信。

因为它更高效和省电,并且它减少了网络使用通过透明的压缩和响应缓存

如果要继续使用HTTP Cilent api请看此文:

http://blog.csdn.net/u011726984/article/details/48528573

说明:

以下为了代码简洁易读,我就不开线程了,但实际使用请在UI线程外。

 public void sendMessage(String username, String password) throws ServiceRulesException {

    HttpURLConnection httpURLConnection = null;
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();

    try {

        String action = "http://10.0.3.2:8080/getUsernameAndPassword.do";      // 请求action
        String requestUrl = Uri.parse(action).buildUpon()       // 建立请求参数
                .appendQueryParameter("loginName", username)    // 默认key-value会被编码为UTF-8
                .appendQueryParameter("loginPwd", password)
                .build()
                .toString();

        URL url = new URL(requestUrl);  // 实例化url
        httpURLConnection = (HttpURLConnection) url.openConnection(); // 打开http连接
        httpURLConnection.setConnectTimeout(5000);
        httpURLConnection.setDoInput(true);     // 允许读取
        httpURLConnection.setDoOutput(true);    // 允许写入,数据发送到服务器,post方式提交,这个必须设置,默认为get方式提交
        // 若不知道返回的body的内容长度,应该使用setChunkedStreamingMode,否则使用setFixedLengthStreamingMode()
        // 如果都不设置,将会导致在传输请求完成之前,请求内容会被强制缓冲在堆内存,浪费内存
        httpURLConnection.setChunkedStreamingMode(0);

        if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new ServiceRulesException("请求连接失败!");
        }

        // 连接成功,获取cookie
        String cookie = null;
        Map<String,List<String>> map = httpURLConnection.getHeaderFields();
        Set<String> set = map.keySet();
        for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
            String key = (String) iterator.next();
            if (key.equals("Set-Cookie")) {
                List<String> list = map.get(key);
                StringBuilder builder = new StringBuilder();
                for (String str : list) {
                    builder.append(str);
                }

                cookie = builder.toString();
                Log.d(TAG, "sendMessage: 第一次得到的cookie=" + cookie);
            }
        }

        // 读取字节流,发送数据或从服务器获取大量的数据,不要使用字节数组读取,应该使用具有缓冲功能的IO读取
        // 因为(input)输入或输出(ouput)流没有被缓冲。
        // HttpURLConnection请求服务器默认使用gzip压缩,getInputStream方法默认自动解压
        reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        String readTmp;
        while ((readTmp = reader.readLine()) != null) {
            sb.append(readTmp);
        }

        // 处理得到的数据sb
        。。。

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 使用完一定要关闭http连接
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }
}

参考:
http://developer.android.com/intl/zh-cn/reference/java/net/HttpURLConnection.html

如有疑问请指出交流!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值