获取头条

来源:互联网 发布:firefox 调试js 编辑:程序博客网 时间:2024/04/28 17:47

    /**
     * 网络上获取头条的数据
     */
    private void getTouTiao() {
        new Thread(){
            @Override
            public void run() {
                try {
                    URL url = new URL("http://www.toutiao.com/hot_words/");

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //设置
                    connection.setRequestMethod("GET");
                    connection.setReadTimeout(5000);
                    connection.setConnectTimeout(5000);

                    //获取
                    int responseCode = connection.getResponseCode();
                    if (responseCode == 200){
                        InputStream inputStream = connection.getInputStream();

                        //将字节流装换为字符串
                        String json = streamToString(inputStream,"utf-8");

                        //字符串发送到主线程解析
                        Message message = Message.obtain();
                        message.what = 0;
                        message.obj = json;
                        handler.sendMessage(message);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();

    }