2

I would like to get a list of all files contained in a directory from http server using Android API having only server's URL. How can i achieve it?

By the way - I have the access to the server if there was anything needed to set up.

thepoosh
  • 12,497
  • 15
  • 73
  • 132
Mariusz
  • 1,825
  • 5
  • 22
  • 36

1 Answers1

2

You have to write a PHP-Script to scan all files on your server for example like that:

<?php
$directory = '/path/to/files';

if ( ! is_dir($directory)) {
    exit('Invalid diretory path');
}

$files = array();

foreach (scandir($directory) as $file) {
    $files[] = $file;
}

var_dump($files);  // YOU HAVE TO WRITE THE OUTPUT AS JSON OR XML
?>

With android you have to only call this script like:

class RequestTask extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
        } catch (IOException e) {
            //TODO Handle problems..
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
    }
}

(To execute the asyncTask:

 new RequestTask().execute("URI to PHP Script");

)

Hope that helps!

zennon
  • 1,080
  • 10
  • 25
  • I dont understand, the ASyncTask expects a URI and you write, that the PHP script has to be passed? – Mariusz May 08 '13 at 08:18