使用Android HttpURLConnection从URL获取文本 [英] Get text from a URL using Android HttpURLConnection

查看:85
本文介绍了使用Android HttpURLConnection从URL获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 HttpURLConnection 获取下面的URL内容并将其放在 TextView 中?

how can i get the content of the URLbelow using HttpURLConnection and put it in a TextView?

http://ephemeraltech.com/demo/android_tutorial20.php

推荐答案

class GetData extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        HttpURLConnection urlConnection = null;
        String result = "";
        try {
            URL url = new URL("http://ephemeraltech.com/demo/android_tutorial20.php");
            urlConnection = (HttpURLConnection) url.openConnection();

            int code = urlConnection.getResponseCode();

            if(code==200){
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                if (in != null) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                    String line = "";

                    while ((line = bufferedReader.readLine()) != null)
                        result += line;
                }
                in.close();
            }

            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        finally {
            urlConnection.disconnect();
        }
        return result;

    }

    @Override
    protected void onPostExecute(String result) {
        yourTextView.setText(result);
        super.onPostExecute(s);
    }
}

并使用

new GetData().execute();

这篇关于使用Android HttpURLConnection从URL获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆