用HttpUrlConnection解析读取数据



new Thread() {
            public void run() {
                setWebsiteInfo("http://172.27.0.200/exam/index.php?m=Index&a=home");
            };
        }.start();

    }

    protected void setWebsiteInfo(String urlStr) {
        // 首先创建URL对象
        try {
            URL url = new URL(urlStr);
            // 通过URL打开连接
            HttpURLConnection openConnection = (HttpURLConnection) url
                    .openConnection();
            // //设置连接超时时间
            // openConnection.setConnectTimeout(5000);
            // //设置读取时间
            // openConnection.setReadTimeout(5000);
            openConnection.connect();

            // 获取响应码
            int code = openConnection.getResponseCode();
            if (code == 200) {
                InputStream is = openConnection.getInputStream();
                byte[] by = new byte[1024];
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                // 将内容读取内存中
                int len = -1;
                while ((len = is.read(by)) != -1) {
                    bos.write(by, 0, len);
                }
                // 关闭流
                is.close();
                final String text = bos.toString("utf-8");
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        mTv.setText(text);

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

    }


你可能感兴趣的:(Android,开发)