使用 Android Web 服务器提供文件夹中的文件

Dra*_*g29 5 webserver android

我想提供本地文件夹的文件(例如 .html 和 .css 文件),以重新创建“真实”本地网站的通常行为。

以下是两个应用程序示例,它们按照我希望的方式工作:Tiny Web Server FreekWS - Android Web Server

我用谷歌搜索了很多,但我找不到任何东西......

我尝试使用NanoHttpd,但似乎我们无法设置根目录或主目录,并且我们只能通过使用Responseserve()方法返回对象来返回一些 http 代码。那不是我想要的。

例如,我希望能够设置一个根目录,sdcard/www/其中index.html包含子文件夹中的图像sdcard/www/img/...

另外,我找到了这个答案,但这不是我想要的。Response它包括使用该方法在对象中返回 .html 文件的内容serve()

我怎样才能做我想做的事?

小智 2

我已经通过以下代码成功地提供了一个文件文件夹...这是我的 Android Web Server 类中的 Response 方法 -->

public Response serve(IHTTPSession session) {
    String uri=session.getUri();
    String msg = "<html><body><h1>Hello server</h1>\n";

    File [] arrayfile;

    int i=0;

    try{
        session.parseBody(new HashMap<String, String>());
    }catch (ResponseException | IOException r){
        r.printStackTrace();
    }


    Map<String, String> parms = session.getParms();
    if (parms.get("username") == null) {
        msg += "<form action='?' method='get'>\n  <p>Your name: <input type='text' name='username'></p>\n" + "</form>\n";
    } else {
        msg += "<p>Hello, " + parms.get("username") + "!</p>";
    }
    msg += "<br><br><a href='/Open_rap'>Open Image of Lionel Messi</a><br><br>";
    msg += "<br><br><a href='/files'>Browse Files</a><br><br>";
    msg += "<br><br><a href='/getmethod'>GET METHOD OPERATION</a><br><br>";
    msg += "<br><br><a href='/postmethod'>POST METHOD OPERATION</a><br><br>";
    msg += "<br><br><a href='/jquery'>JQUERY OPERATION</a><br><br>";
    if(uri.equals("/hello")){
            String response="Hello World";
            return  newFixedLengthResponse(response);
    }
    else if(uri.equals("/getmethod")){
        String html="<html><head><h1>Welcome to the Form</h1><head/><body>";

        if(parms.get("name")==null){
            html +="<form action='' method='get'> \n " +
                    "<p>Enter Your Name:</p> <input type='text' name='name'>" +
                    "</form>" +
                    "</body>";
        }
        else{
            html +="<p>Hello Mr. "+ parms.get("name") +"</p>"+
                    "</body> ";
        }

        html +="</html>";
        return newFixedLengthResponse(html);

    }
    else if(uri.equals("/postmethod")){
        String html="<html><head><h1>Welcome to the Form</h1><head/><body>";
        Map<String, String> files = new HashMap<String, String>();
        Method method = session.getMethod();
        String postParameter="";


        html +="<form action='' method='post'> \n " +
                "<p>Enter Your Name:</p> <input type='text' name='name'>" +
                "</form>";

        if (Method.POST.equals(method) || Method.PUT.equals(method)) {
            try {
                session.parseBody(files);
            } catch (IOException ioe) {
                try {
                   // return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("Exception", e.getMessage());
                }
            } catch (ResponseException re) {
                try {
                   // return newFixedLengthResponse(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d("Exception", re.getMessage());
                }
            }
        }
        html +="</body></html>";
        String postBody = session.getQueryParameterString();
        postParameter = session.getParms().get("name");
        Log.d("Postbody",postBody+"\n"+postParameter);
        if(postParameter!=null){
            String html1="<html><head><h1>"+ postParameter +"</h1><head></html>";
            return newFixedLengthResponse(html1);
        }
        return newFixedLengthResponse(Response.Status.OK,"text/html",html);
    }

    else if(uri.equals("/Open_rap")){

        File root= Environment.getExternalStorageDirectory();
        FileInputStream fis = null;
        File file = new File(root.getAbsolutePath() + "/www/messi.jpg");
        try{
            if(file.exists())
            {
                fis = new FileInputStream(file);

            }
            else
                Log.d("FOF :", "File Not exists:");
        }catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }


        return newFixedLengthResponse(Response.Status.OK,"image/jpeg",fis, file.length() );
    }

    else if(uri.equals("/files")) {
        File root = Environment.getExternalStorageDirectory();

        FileInputStream fis = null;
        File file = new File(root.getAbsolutePath() + "/www/files/");
        arrayfile = file.listFiles();
        String html = "<html><body><h1>List Of All Files</h1>";
        for (i = 0; i < arrayfile.length; i++) {
            Log.d("Files", "FileName:" + arrayfile[i].getName());
            html += "<a href='/www/files/" + arrayfile[i].getName() + "' >" + arrayfile[i].getName() + "</a><br><br>";

        }
        html += "</body></html>";

        return newFixedLengthResponse(html);
    }


    else if(uri.equals("/jquery")){
        String address="http://"+MainActivity.ipaddress+":8080/jquery-3.3.1.min.js";
        Log.d("IP",address);
        String s="<html>\n" +
                "<head>\n" +
            //    "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n" +
             //   "<script src='file:///android_asset/js/jquery-3.3.1.min.js' type='text/javascript'></script>\n" +
               "<script src='"+address+"'></script>\n" +
                "<script>\n" +
                "$(document).ready(function(){\n" +
                "    $(\"button\").click(function(){\n" +
                "        $(\"p\").toggle();\n" +
                "    });\n" +
                "});\n" +
                "</script>\n" +
                "</head>\n" +
                "<body>\n" +
                "\n" +
                "<h2>This is a heading</h2>\n" +
                "\n" +
                "<button>Click me to hide paragraphs</button>\n" +
                "<p>This is a paragraph.</p>\n" +
                "<p>This is another paragraph.</p>\n" +
                "\n" +
                "\n" +
                "</body>\n" +
                "</html>\n";
        return newFixedLengthResponse(s);

    }
    else if(uri.equals("/jquery-3.3.1.min.js")){

        File root= Environment.getExternalStorageDirectory();
        FileInputStream fis = null;
        File file = new File(root.getAbsolutePath() + "/www/resources/jquery-3.3.1.min.js");
        Log.d("Jquery","hello");
        try{
            if(file.exists())
            {
                fis = new FileInputStream(file);

            }
            else
                Log.d("FOF :", "File Not exists:");
        }catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }


        return newFixedLengthResponse(Response.Status.OK,"application/javascript",fis, file.length() );
    }

    else if(uri.contains(".")){

        String[] split=uri.split("/");
        String s="";
        for (i=0;i<split.length;i++){
            Log.d("String",""+split[i]+""+i);
            s=s+"/"+split[i];
        }
        String x=s.substring(1,s.length());
        Log.d("String2",s);
        Log.d("String2",x+"  "+x.length());
        String y = NanoHTTPD.getMimeTypeForFile(x);
        Log.d("MIME-TYPE",y);
        File root= Environment.getExternalStorageDirectory();
        FileInputStream fis = null;
        //File file = new File(root.getAbsolutePath() + "/"+split[1]+"/"+split[2]+"/"+split[3]);
        File file=new File(root.getAbsolutePath()+x);
        try{
            if(file.exists())
            {
                fis = new FileInputStream(file);

            }
            else
                Log.d("FOF :", "File Not exists:");
        }catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

        return newFixedLengthResponse(Response.Status.OK,y,fis, file.length() );

    }

    else {
        return newFixedLengthResponse(msg + "</body></html>\n");
    }

}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的, uri.contains(.)
这部分代码是我使用root文件对象实现文件夹的部分,并且 file input stream 我的文件保存在我的 Android 设备的内部存储中,/www/files 如果您有任何问题,请告诉我。