我想使用只有服务器 URL 的 Android API 从 http 服务器获取目录中包含的所有文件的列表。我怎样才能实现它?
顺便说一句 - 如果需要设置任何东西,我可以访问服务器。
您必须编写一个 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");
)
希望有帮助!