0

I am trying to use nanoHTTP in an Android App to serve a file index.html placed in raw directory.

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();
}

This code loads index.html for the first time flawlessly, but if I refresh the page then answer is empty string. What am I doing wrong ?

Manmohan Bishnoi
  • 791
  • 13
  • 37

1 Answers1

0

Ok I found my mistake from this page Getting an InputStream to read more than once, regardless of markSupported()

InputStream can be read only once. I modified the code to reopen the InputStream every time the App needs to serve the page.

Modified code is here : 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);
    }

and add finally block in convertStreamToString function to close the InputStream.

    finally {
        try {
            is.close();
        } catch (IOException e) {
            Log.w("LOG", e.getMessage());
        }
    }
Community
  • 1
  • 1
Manmohan Bishnoi
  • 791
  • 13
  • 37
  • 1
    Wrapping the `InputStream` with a [BufferedInputStream](http://docs.oracle.com/javase/6/docs/api/java/io/BufferedInputStream.html) will guarantee the stream supports `mark()` and `reset()`. – MDrabic Oct 10 '13 at 14:41