使用来自 Android 的 Nanohttpd 服务 font/images

Serve font/images with Nanohttpd from Android

我正在尝试使用 nanohttpd 托管一个 Angular 应用程序,因此我将文件放入 android 应用程序的资产文件夹内的 dist/ 文件夹中。现在我想提供 angular 文件,但我在控制台中不断收到此类错误(它仅在尝试请求字体和图像时出现):

GET http://hostname/font.woff2 200 (OK)

这是我用来提供文件的代码:

public Response serve(IHTTPSession session) {
    String filepath = getFilepath(session.getUri()); // Get filepath depending on the requested url
    String mimeType = getMimeType(filepath); // Get mimetype depending on the extension of the filepath (font/woff, font/woff2, font/ttf, image/x-icon, text/html, application/javascript)
    String content;
    byte[] buffer;
    Response res;
    InputStream is;
    try {
        is = this.assetManager.open("dist/" + filepath);
        int size = is.available();

        buffer = new byte[size];
        is.read(buffer);
        is.close();

        content = new String(buffer);
        content = content.replace("old string", "new string");

        if (typeText(mimeType)) { // If mimeType is text/html or application/json
            res = newFixedLengthResponse(content);
        }else{ // This is when I try to serve fonts or images
            res = newFixedLengthResponse(Response.Status.OK, mimeType, is, size); // Not working
        }

    }catch(IOException e) {
        res = newFixedLengthResponse("Error!");
    }
    return res;
}

我认为可能是字体文件被压缩了,或者大小不是 InputStream 的实际大小。此外,在加载页面时,vendor.js 需要大量下载,之后,它会停止下载其余文件。

我在 logcat 上也遇到了这个错误:

Communication with the client broken, or an bug in the handler code

我是这样修复的:

public Response serve(IHTTPSession session) {
    String filepath = getFilepath(session.getUri()); // Get filepath depending on the requested url
    String mimeType = getMimeType(filepath); // Get mimetype depending on the extension of the filepath (font/woff, font/woff2, font/ttf, image/x-icon, text/html, application/javascript)
    String content;
    byte[] buffer;
    Response res;
    InputStream is;
    try {
        is = this.assetManager.open("dist/" + filepath);
        if (!typeText(mimeType)) { // If mimeType is font/<something> or image/<something>
            return newFixedLengthResponse(Response.Status.OK, mimeType, is, -1);
        }
        int size = is.available();
        buffer = new byte[size];
        is.read(buffer);
        is.close();
        content = new String(buffer);
        content = content.replace("old string", "new string");
    }catch(IOException e) {
        content = "Error!";
    }
    return newFixedLengthResponse(content);
}

我真的不知道发生了什么,但这种方式效果很好。在我看来,is.available() 没有返回正确的文件大小。