Home > DeveloperSection > Forums > How to download string from webpage in android
Norman Reedus
Norman Reedus

Total Post:45

Points:315
Posted on    November-07-2014 3:56 AM

 Android Java 
Ratings:


 1 Reply(s)
 1430  View(s)
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?



Sanjay Sharma
Sanjay Sharma

Total Post:45

Points:315
Posted on    November-07-2014 6:10 AM

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

Don't want to miss updates? Please click the below button!

Follow MindStick