Advertise with us

How to download string from webpage in android

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?

Last updated:11/7/2014 6:10:42 AM

1 Answers

Sanjay Sharma
Sanjay Sharma

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