Sunday, August 10, 2014

How to access a webpage/URL in Android using Apache .htaccess/.htpasswd password authentication

You can't download a webpage in the main thread.  You have to create an asynchronous task.  Here's how to do that:

Create a class called RetrieveFeedTask (change the hilighted text):


class RetrieveFeedTask extends AsyncTask<String, Void, Long> {

    private Exception exception;

    @SuppressLint("NewApi") protected Long doInBackground(String urlParam) {

     try 
   {
       DefaultHttpClient client = new DefaultHttpClient();
       client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials("username", "password")); 
       HttpGet request = new HttpGet(urlParam);
       
       HttpResponse response = client.execute(request);
        
       HttpEntity entity = response.getEntity();
       InputStream inputStream = entity.getContent();
       
       StringWriter writer = new StringWriter();
       String encoding = StandardCharsets.UTF_8.name();
       IOUtils.copy(inputStream, writer, encoding);
       
       StringBuffer sb = writer.getBuffer(); 
       String finalstring = sb.toString();
        
   } 
   catch (IOException e) 
   {
       // TODO Auto-generated catch block
       e.printStackTrace();
   }
    catch (Exception e)
    {
e.printStackTrace();
    }
   
    return new Long(0L);
   
    }

     @Override
     protected Long doInBackground(String... arg0) {
return this.doInBackground(arg0[0]);
     }
}


In your activity file, open the url like this:

String url = "http://www.myPasswordProtectedWebServer.com";
new RetrieveFeedTask().execute(url);



In your AndroidManfiest.xml file, be sure to add the following:

<uses-permission android:name="android.permission.INTERNET"/>


Solution derived from http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception

No comments: