1

使用下面的代码,我能够使用 Nanohttpd 轻量级服务器在 android 手机上创建移动服务器。该代码基本上循环通过主机android设备的根目录并将文件和文件夹列为链接。我要实现的是当用户单击任何链接(文件夹链接)时,浏览器应显示单击的文件夹链接中包含的文件和文件夹。我该怎么做,因为我找不到任何适合初学者的 Nanohttpd 文档。

import java.io.File;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.widget.TextView;

public class MainActivity extends Activity {
    private static final int PORT = 8080;
    private TextView hello;
    private WebServer server;
    private Handler handler = new Handler();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        hello = (TextView) findViewById(R.id.hello);
    }

    /*
     * There are some earlier versions of android that can not implement this
     * method of getting IP address and isEmpty() method. The
     * 
     * @SupreesLint("NewAPI") helps to suppress the error that will arise in
     * such devices when implementing these methods . For the application
     * however, a minimum version of API that can be able to execute the
     * application flawlessly is set. The enables error checking as lower
     * version that can not implement this methods wouldn't be able to install
     * the application.
     */
    @SuppressLint("NewApi")
    @Override
    protected void onResume() {
        super.onResume();

        TextView textIpaddr = (TextView) findViewById(R.id.ipaddr);
        if (Utils.getIPAddress(true).trim().isEmpty()) {
            textIpaddr.setText(Utils.getIPAddress(false) + ":" + PORT);
        } else {
            textIpaddr.setText(Utils.getIPAddress(true) + ":" + PORT);
        }

        try {
            server = new WebServer();
            server.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String intToIp(int i) {

        return ((i >> 24) & 0xFF) + "." + ((i >> 16) & 0xFF) + "."
                + ((i >> 8) & 0xFF) + "." + (i & 0xFF);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (server != null)
            server.stop();
    }

    private class WebServer extends NanoHTTPD {

        public WebServer() {
            super(8080);
        }

        @Override
        public Response serve(String uri, Method method,
                Map<String, String> header, Map<String, String> parameters,
                Map<String, String> files) {
            File rootDir = Environment.getExternalStorageDirectory();
            File[] files2 = rootDir.listFiles();
            String answer = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>sdcard0 - TECNO P5 - WiFi File Transfer Pro</title>";
            for (File detailsOfFiles : files2) {
                answer += "<a href=\"" + detailsOfFiles.getAbsolutePath()
                        + "\" alt = \"\">" + detailsOfFiles.getAbsolutePath()
                        + "</a><br>";
            }
            answer += "</head></html>";
            return new NanoHTTPD.Response(answer);
        }



    }

}

这是我的浏览器中输出的样子

4

3 回答 3

5

经过足够的时间研究 NanoHTTPD 框架后,我终于弄清楚了如何做到这一点。下面的代码帮助我在主机 android 设备的目录中导航:

@Override
        public Response serve(String uri, Method method,
                Map<String, String> header, Map<String, String> parameters,
                Map<String, String> files) {
            File rootDir = Environment.getExternalStorageDirectory();
            File[] filesList = null;
            String filepath = "";
            if (uri.trim().isEmpty()) {
                filesList = rootDir.listFiles();
            } else {
                filepath = uri.trim();
            }
            filesList = new File(filepath).listFiles();
            String answer = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>sdcard0 - TECNO P5 - WiFi File Transfer Pro</title>";
            if (new File(filepath).isDirectory()) {
                for (File detailsOfFiles : filesList) {
                    answer += "<a href=\"" + detailsOfFiles.getAbsolutePath()
                            + "\" alt = \"\">"
                            + detailsOfFiles.getAbsolutePath() + "</a><br>";
                }
            } else {
            }
            answer += "</head></html>" + "uri: " + uri + " \nfiles " + files
                    + " \nparameters " + parameters + " \nheader ";
            return new NanoHTTPD.Response(answer);
        }

Response Method中的uri参数包含当时的浏览器url:例如,如果地址栏上显示的url是:/192.168.43.1:8080/storage/sdcard1/Smadav_2012_Rev._9.0,则uri包含/storage/sdcard1 /Smadav_2012_Rev._9.0。我所做的只是将 uri 作为文件路径传递,当然,当 uri 为空时,第一次连接不是这种情况。

于 2014-05-14T17:51:08.853 回答
4

您在第一个参数中获得 URI。因此,将其附加到打开指定目录的路径。如果您请求 192.168.1.6:8080/ABC 程序将在外部目录中查找 ABC 文件夹。

然后,当检查所取的项目是文件还是目录时,我们会根据它来更改输出。使用

.isFile()

下面是应该工作的代码:

 ....
 public Response serve(String uri, Method method,
                Map<String, String> header, Map<String, String> parameters,
                Map<String, String> files) {

            File rootDir = new File( Environment.getExternalStorageDirectory() +  File.separator  + uri);
            File[] files2 = rootDir.listFiles();
            String answer = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>sdcard0 - TECNO P5 - WiFi File Transfer Pro</title>";
            for (File detailsOfFiles : files2) {
                if(detailsOfFiles.isFile()){
                        answer += detailsOfFiles.getAbsolutePath() + "<br>";
                }else{
                answer += "<a href=\"" + detailsOfFiles.getAbsolutePath()
                        + "\" alt = \"\">" + detailsOfFiles.getAbsolutePath()
                        + "</a><br>";
                        }
            }
            answer += "</head></html>";
            return new NanoHTTPD.Response(answer);
 }
...

抱歉解释不好。

于 2014-05-13T09:37:33.827 回答
0

更新:上面的代码似乎工作得很好。但它似乎也太老了。这是 nanohttpd 库更新的代码。

public Response serve(IHTTPSession session) {
        File rootDir = new File( Environment.getExternalStorageDirectory() +  File.separator  + session.getUri());
        File[] files2 = rootDir.listFiles();
        String answer = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>sdcard0 - TECNO P5 - WiFi File Transfer Pro</title>";
        for (File detailsOfFiles : files2) {
            if(detailsOfFiles.isFile()){
                answer += detailsOfFiles.getAbsolutePath() + "<br>";
            }else{
                answer += "<a href=\"" + detailsOfFiles.getAbsolutePath()
                        + "\" alt = \"\">" + detailsOfFiles.getAbsolutePath()
                        + "</a><br>";
            }
        }
        answer += "</head></html>";
        return newFixedLengthResponse(answer);
    }

希望对您有所帮助

于 2021-08-24T05:41:27.153 回答