Get text from a URL using Android HttpURLConnection

元气小坏坏 提交于 2021-02-18 07:58:27

问题


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

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


回答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);
    }
}

and call this class by using

new GetData().execute();


来源:https://stackoverflow.com/questions/32964827/get-text-from-a-url-using-android-httpurlconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!