我想使用仅具有服务器URL的Android API从http服务器获取目录中包含的所有文件的列表。我怎样才能实现它?
顺便说一下 - 如果有任何需要设置,我可以访问服务器。
答案 0 :(得分: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");
)
希望有所帮助!