3

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

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

Lii
  • 11,553
  • 8
  • 64
  • 88
mahdi azarm
  • 340
  • 2
  • 7
  • 18
  • http://stackoverflow.com/a/8655039/5202007 – Mohammad Tauqir Oct 06 '15 at 08:12
  • Possible duplicate of [Http Get using Android HttpURLConnection](http://stackoverflow.com/questions/8654876/http-get-using-android-httpurlconnection) – Mel Oct 06 '15 at 08:20
  • thanks i seen this before asking but it doesn't help me the content in the url is "TUTORIAL 20 WORKED, WE GOT CONNECTION" and i want to get this text from url then put it in a text view – mahdi azarm Oct 06 '15 at 08:20

1 Answers1

14
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();
Deepak Goyal
  • 4,747
  • 2
  • 21
  • 46