HOW TO DOWNLOAD STRING FROM WEBPAGE IN ANDROID

Norman Reedus

Total Post:45

Points:315
Posted by  Norman Reedus
Java 
 1807  View(s)
Ratings:
Rate this:

I am making an app that will download a string from a website and display it. I tried many examples online and I've literally been searching for days for this, but I can't find a single solution.

From what I have read, I know I have to get the content of the url from another thread, but no tutorial showed me how to do this.

I have a textview on the layout and that will be where the html content will have to show up.

Can anybody show me an example of how this is done?

  1. Sanjay Sharma

    Post:45

    Points:315
    Re: How to download string from webpage in android

    What about something like this?

    public class MyAsyncTask extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... requestUrl) 
        {
            String result = null;
    
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(requestUrl[0]);
    
            try
            {
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                result = httpClient.execute(request, responseHandler);
            }
            catch (IOException e)
            {
                Log.e("requestStringFromWebServer", "Whoops!", e);
            }
    
            httpClient.getConnectionManager().shutdown();
    
            return result;
        }
    
        @Override
        protected void onPostExecute(String result)
        {
            if (result != null)
            {
                // Handle the result from your request here...
            }
        }
    }

    And kick it off with

    String myUrlStr; // Initialize this to your url
    new MyAsyncTask().execute(myUrlStr);

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!