Java读取网络数据(新浪网址)InputStream的数据流操作实录笔记(二) 分享出来供大家参考!(

本文深入探讨了新浪如何优化网络Stream读取过程,将其转换为字符串。通过详细分析源代码,揭示了关键步骤,包括使用BufferedReader、InputStreamReader以及UTF-8编码,确保高效且准确地获取响应体内容。同时,文章特别关注了在不同环境(如Dalvik)下的特殊处理,确保代码的通用性和兼容性。

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

上一篇是自己写的网络Stream读取并转换成String的源代码,今天研究了一下新浪的写法,下面贴出来供大家参考>>:

/**
     * Returns the response body as string.<br>
     * Disconnects the internal HttpURLConnection silently.
     * @return response body
     * @throws WeiboException
     */
    public String asString() throws WeiboException{
        if(null == responseAsString){
            BufferedReader br;
            try {
                InputStream stream = asStream();
                if (null == stream) {
                    return null;
                }
                br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
                StringBuffer buf = new StringBuffer();
                String line;
                while (null != (line = br.readLine())) {
                    buf.append(line).append("\n");
                }
                this.responseAsString = buf.toString();
                if(Configuration.isDalvik()){
                    this.responseAsString = unescape(responseAsString);
                }
                log(responseAsString);
                stream.close();
                con.disconnect();
                streamConsumed = true;
            } catch (NullPointerException npe) {
                // don't remember in which case npe can be thrown
                throw new WeiboException(npe.getMessage(), npe);
            } catch (IOException ioe) {
                throw new WeiboException(ioe.getMessage(), ioe);
            }
        }
        return responseAsString;
    }


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值