0

我正在尝试在 Android 应用程序中使用 nanoHTTP 来提供放置在原始目录中的文件 index.html。

MainActivity.java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    .
    .
    .
    r = getResources();
    is = r.openRawResource(R.raw.index);

MyWebServer.java

    @Override
    public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parms, Map<String, String> files) {
    .
    .
    .
    answer = convertStreamToString(this.mainFile);
    return new NanoHTTPD.Response(answer);
    }

    private static String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append((line + "\n"));
        }
    } catch (IOException e) {
        Log.w("LOG", e.getMessage());
    }
    return sb.toString();
}

此代码首次完美加载 index.html,但如果我刷新页面,则答案为空字符串。我究竟做错了什么 ?

4

1 回答 1

0

好的,我从这个页面中发现了我的错误Get an InputStream to read more than once,不管 markSupported()

InputStream只能读取一次。每次应用需要为页面提供服务时,我都会修改代码以重新打开 InputStream。

修改后的代码在这里:MyWebServer.java

    @Override
    public Response serve(String uri, Method method, Map<String, String> header, Map<String, String> parms, Map<String, String> files) {
    .
    .
    .
    this.mainFile = this.mr.openRawResource(R.raw.index);
    answer = convertStreamToString(this.mainFile);
    return new NanoHTTPD.Response(answer);
    }

并在convertStreamToString函数中添加finally块以关闭 InputStream。

    finally {
        try {
            is.close();
        } catch (IOException e) {
            Log.w("LOG", e.getMessage());
        }
    }
于 2013-10-10T14:37:20.117 回答