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

3
  • stackoverflow.com/a/8655039/5202007 Commented Oct 6, 2015 at 8:12
  • Possible duplicate of Http Get using Android HttpURLConnection Commented Oct 6, 2015 at 8: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 Commented Oct 6, 2015 at 8:20

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

6 Comments

thanks man it's worked but can i do that without create a class?
it is network operation and must be perform on separate thread. So you need the asyncTask class. Because asynctask is the best option to perform network operations.
Depreciated now
@DeepakGoyal : Yep already seen it. stackoverflow.com/questions/29150184/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.