欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android网络流读取实现方法

程序员文章站 2022-04-22 17:58:17
网络流读取的步骤: 1、添加联网权限 2、获取网络数据流 URL url = new URL(...

网络流读取的步骤:

1、添加联网权限

   

2、获取网络数据流

URL url = new URL(
                                    "https://suggest.taobao.com/sug?code=utf-8&q=%E6%89%8B%E6%9C%BA&callback=cb");
                            HttpURLConnection connection = (HttpURLConnection) url
                                    .openConnection();
                            InputStream in = connection.getInputStream();

3、把网络流转化为字符串

String result = StreamTools.readFromStream(in);

/**
     * @param is 输入流
     * @return String 返回的字符串
     * @throws IOException 
     */
    public static String readFromStream(InputStream is) throws IOException{
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while((len = is.read(buffer))!=-1){
            baos.write(buffer, 0, len);
        }
        is.close();
        String result = baos.toString();
        baos.close();
        return result;
    }