亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在本地主機上使用 nanohttpd 作為服務器,如何在整個目錄中提供靜態 HTML 代碼?

在本地主機上使用 nanohttpd 作為服務器,如何在整個目錄中提供靜態 HTML 代碼?

智慧大石 2023-04-26 16:42:25
我無法讓 nanohttpd 工作。似乎無法www在應用程序的根目錄中找到該目錄。我的代碼在https://github.com/tlkahn/neonx我在 MainActivity.java 的代碼:@Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        BottomNavigationView navView = findViewById(R.id.nav_view);        mWebView = findViewById(R.id.webkit);        navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);        WebSettings webSettings = mWebView.getSettings();        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);        webSettings.setDomStorageEnabled(true);        mWebView.getSettings().setLoadsImagesAutomatically(true);        mWebView.getSettings().setJavaScriptEnabled(true);        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);        mWebView.setWebViewClient(new WebViewClient() {            @Override            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {                return false;            }        });        if (!haveNetworkConnection()) {            new AlertDialog.Builder(this)                .setTitle("You are not connected to internet.")                .setMessage("Are you sure you want to exit?")                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        finishAffinity();                        System.exit(0);                    }                }).setNegativeButton("No", null).show();        }        startLocalServer(3000, "www", true, true );    }當我嘗試訪問時localhost:3000,出現錯誤:給定路徑不是目錄。錯誤似乎來自這一行: https: //git.io/fjS3f我猜我初始化 rootDir 的方式是錯誤的(這一行:https: //git.io/fjS3v)。但是我怎樣才能使這項工作呢?我的意思是服務整個目錄,這意味著所有 CSS/JS/hypyerlinks 應該工作,一旦 nanohttpd 開始服務......
查看完整描述

2 回答

?
吃雞游戲

TA貢獻1829條經驗 獲得超7個贊

問題是您無法像訪問本地文件一樣訪問 assets 文件夾中的文件。您必須擴展 NanoHTTPD 并覆蓋 serve(IHTTPSession) 才能提供資產。這是 Kotlin 中的示例。如果您看不懂,請告訴我,我會將其移植到 Java。


class FileServer(private val context: Context, port: Int) : NanoHTTPD(port) {

override fun serve(session: IHTTPSession): Response {

    val uri = session.uri.removePrefix("/").ifEmpty { "index.html" }

    println("Loading $uri")

    try {

        val mime = when (uri.substringAfterLast(".")) {

            "ico" -> "image/x-icon"

            "css" -> "text/css"

            "htm" -> "text/html"

            "html" -> "text/html"

            else -> "application/javascript"

        }


        return NanoHTTPD.newChunkedResponse(

            Response.Status.OK,

            mime,

            context.assets.open("www/$uri") // prefix with www because your files are not in the root folder in assets

        )

    } catch (e: Exception) {

        val message = "Failed to load asset $uri because $e"

        println(message)

        e.printStackTrace()

        return NanoHTTPD.newFixedLengthResponse(message)

    }

}


查看完整回答
反對 回復 2023-04-26
?
慕后森

TA貢獻1802條經驗 獲得超5個贊

輸出:

http://img1.sycdn.imooc.com//6448e42d0001e48606511196.jpg

日志貓:


2019-08-05 15:21:53.838 10650-10650/com.neonxorg.neonx E/MainActivity: -------Assets List-----

2019-08-05 15:21:53.838 10650-10650/com.neonxorg.neonx E/MainActivity: asset-manifest.json

2019-08-05 15:21:53.838 10650-10650/com.neonxorg.neonx E/MainActivity: favicon.ico

2019-08-05 15:21:53.838 10650-10650/com.neonxorg.neonx E/MainActivity: index.html

2019-08-05 15:21:53.838 10650-10650/com.neonxorg.neonx E/MainActivity: manifest.json

2019-08-05 15:21:53.838 10650-10650/com.neonxorg.neonx E/MainActivity: precache-manifest.81af63d07b6dd6ae8e331187c522b020.js

2019-08-05 15:21:53.838 10650-10650/com.neonxorg.neonx E/MainActivity: service-worker.js

2019-08-05 15:21:53.838 10650-10650/com.neonxorg.neonx E/MainActivity: static

2019-08-05 15:21:53.842 10650-10650/com.neonxorg.neonx E/MainActivity: copyFolderFromAssets rootDirFullPath-www targetDirFullPath-/storage/emulated/0/Android/data/com.neonxorg.neonx/cache/www

2019-08-05 15:21:53.865 10650-10650/com.neonxorg.neonx E/MainActivity: copyFolderFromAssets rootDirFullPath-www/static targetDirFullPath-/storage/emulated/0/Android/data/com.neonxorg.neonx/cache/www/static

2019-08-05 15:21:53.867 10650-10650/com.neonxorg.neonx E/MainActivity: copyFolderFromAssets rootDirFullPath-www/static/css targetDirFullPath-/storage/emulated/0/Android/data/com.neonxorg.neonx/cache/www/static/css

2019-08-05 15:21:53.922 10650-10650/com.neonxorg.neonx E/MainActivity: copyFolderFromAssets rootDirFullPath-www/static/js targetDirFullPath-/storage/emulated/0/Android/data/com.neonxorg.neonx/cache/www/static/js

2019-08-05 15:21:54.352 10650-10650/com.neonxorg.neonx E/MainActivity: copyFolderFromAssets rootDirFullPath-www/static/media targetDirFullPath-/storage/emulated/0/Android/data/com.neonxorg.neonx/cache/www/static/media

2019-08-05 15:21:54.526 10650-10650/com.neonxorg.neonx E/MainActivity: -------Root File List-----

2019-08-05 15:21:54.528 10650-10650/com.neonxorg.neonx E/File: /storage/emulated/0/Android/data/com.neonxorg.neonx/cache/www/precache-manifest.81af63d07b6dd6ae8e331187c522b020.js

2019-08-05 15:21:54.528 10650-10650/com.neonxorg.neonx E/File: /storage/emulated/0/Android/data/com.neonxorg.neonx/cache/www/service-worker.js

2019-08-05 15:21:54.528 10650-10650/com.neonxorg.neonx E/File: /storage/emulated/0/Android/data/com.neonxorg.neonx/cache/www/static

2019-08-05 15:21:54.528 10650-10650/com.neonxorg.neonx E/File: /storage/emulated/0/Android/data/com.neonxorg.neonx/cache/www/favicon.ico

2019-08-05 15:21:54.528 10650-10650/com.neonxorg.neonx E/File: /storage/emulated/0/Android/data/com.neonxorg.neonx/cache/www/manifest.json

2019-08-05 15:21:54.528 10650-10650/com.neonxorg.neonx E/File: /storage/emulated/0/Android/data/com.neonxorg.neonx/cache/www/asset-manifest.json

2019-08-05 15:21:54.528 10650-10650/com.neonxorg.neonx E/File: /storage/emulated/0/Android/data/com.neonxorg.neonx/cache/www/index.html

2019-08-05 15:21:54.704 10650-10650/com.neonxorg.neonx E/MainActivity: Connected : Please access! http://192.168.1.2:3000 From a web browser

代碼:


public final String TAG = getClass().getSimpleName();

public void startLocalServer(int port, String root, Boolean localhost, Boolean keepAlive) {

        try {

            String[] filePathList = (getAssets().list("www"));

            Log.e(TAG,"-------Assets List-----");

            for (String s : filePathList) {

                Log.e(TAG, s);

            }

            File externalCache = getExternalCacheDir();

            if (externalCache != null) {

                String path = externalCache.getAbsolutePath() + "/" + root;

                copyFolderFromAssets(getApplicationContext(), "www", path);

                File www_root = new File(path);

                Log.e(TAG,"-------Root File List-----");

                for (File f : www_root.listFiles()) {

                    Log.e("File ", f.getAbsolutePath());

                }

                server = new WebServer("localhost", port, www_root.getCanonicalFile());

                server.start();

                printIp();

            }


        } catch (IOException e) {

            Log.e(TAG, Log.getStackTraceString(e));

        }

    }


    public void copyFolderFromAssets(Context context, String rootDirFullPath, String targetDirFullPath) {

        Log.e(TAG,"copyFolderFromAssets " + "rootDirFullPath-" + rootDirFullPath + " targetDirFullPath-" + targetDirFullPath);

        File file = new File(targetDirFullPath);

        if (!file.exists()) {

            new File(targetDirFullPath).mkdirs();

        }

        try {

            String[] listFiles = context.getAssets().list(rootDirFullPath);// 遍歷該目錄下的文件和文件夾

            for (String string : listFiles) {// 看起子目錄是文件還是文件夾,這里只好用.做區分了

                if (isFileByName(string)) {// 文件

                    copyFileFromAssets(context, rootDirFullPath + "/" + string, targetDirFullPath + "/" + string);

                } else {// 文件夾

                    String childRootDirFullPath = rootDirFullPath + "/" + string;

                    String childTargetDirFullPath = targetDirFullPath + "/" + string;

                    new File(childTargetDirFullPath).mkdirs();

                    copyFolderFromAssets(context, childRootDirFullPath, childTargetDirFullPath);

                }

            }

        } catch (IOException e) {

            Log.e(TAG, Log.getStackTraceString(e));

        }

    }



    public void copyFileFromAssets(Context context, String assetsFilePath, String targetFileFullPath) {

        InputStream assestsFileInputStream;

        try {

            assestsFileInputStream = context.getAssets().open(assetsFilePath);

            FileOutputStream fOS = new FileOutputStream(new File(targetFileFullPath));

            int length = -1;

            byte[] buf = new byte[1024];

            while ((length = assestsFileInputStream.read(buf)) != -1) {

                fOS.write(buf, 0, length);

            }

            fOS.flush();

        } catch (IOException e) {

            Log.e(TAG, Log.getStackTraceString(e));

        }

    }


    private boolean isFileByName(String str) {

        return str.contains(".");

    }


    private void printIp() {

        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);

        int ipAddress = wifiManager.getConnectionInfo().getIpAddress();

        final String formatedIpAddress = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff),

                (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));

        Log.e(TAG,"Connected : " + "Please access! http://" + formatedIpAddress + ":" + server.getListeningPort() + " From a web browser");

    }

給定路徑不是目錄。


當 nanphttpd 無法定位數據時,它會給出此錯誤。


為什么你沒有得到實際的錯誤


在你正在使用的catch 塊中,copyFolderFromAssets由于僅顯示選定的應用程序過濾器,它可能不會顯示在你的 LogCat 上copyFileFromAssetse.printStackTrace()

http://img1.sycdn.imooc.com//6448e44400015e4815620066.jpg

為了打印錯誤,您需要使用以下內容:


Log.e(TAG, Log.getStackTraceString(e));

我用 Log.e 語句替換了所有 System.out 和 e.printStackTrace。應用程序很可能無法將內容從 www 目錄復制到目標目錄。我將目標目錄更改為緩存目錄,它在我的設備上運行。(見下文):


File externalCache = getExternalCacheDir();

if (externalCache != null) {

    String path = externalCache.getAbsolutePath() + "/" + root;

    File www_root = new File(path);

    copyFolderFromAssets(getApplicationContext(), "www", path);

    Log.e(TAG,"-------Root File List-----");

    for (File f : www_root.listFiles()) {

        Log.e("File ", f.getAbsolutePath());

    }

    server = new WebServer("localhost", port, www_root.getCanonicalFile());

    server.start();

    printIp();

}

邊注:


static除非或除非您想將它們復制到實用程序類中,否則無需在這些函數中使用關鍵字


查看完整回答
反對 回復 2023-04-26
  • 2 回答
  • 0 關注
  • 271 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號