【问题标题】:Get text from a URL using Android HttpURLConnection使用 Android HttpURLConnection 从 URL 获取文本
【发布时间】:2016-01-03 01:37:06
【问题描述】:

如何使用HttpURLConnection 获取以下 URL 的内容并将其放入TextView

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

【问题讨论】:

标签: android httpurlconnection


【解决方案1】:
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();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-29
  • 2012-11-06
  • 1970-01-01
  • 2018-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多