使用Android的Nanohttpd服务字体/图像

时间:2018-08-12 04:24:24

标签: android angular inputstream nanohttpd

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

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

1 个答案:

答案 0 :(得分:0)

我这样修复:

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()没有返回正确的文件大小。