如何从http服务器列出目录中的所有文件?

问题描述 投票:2回答:1

我想从使用仅具有服务器URL的Android API的http服务器获取目录中包含的所有文件的列表。我怎样才能实现它?

顺便说一句 - 如果有任何需要设置,我可以访问服务器。

java http
1个回答
1
投票

您必须编写PHP脚本来扫描服务器上的所有文件,例如:

<?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
?>

使用android你只需要调用这个脚本:

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..
    }
}

(要执行asyncTask:

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

)

希望有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.