mahdi azarm mahdi azarm - 25 days ago 4
Android Question

get text from a url using android httpurlconnection

how can i get the content of the url below using HttpURLConnection and put it in a Textview ?

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

Answer
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();