androidgoogle-casthttpservernanohttpd

NanoHTTPD serves empty file


I'm trying to add Google Cast functionality to a media app of mine which primarily deals with locally stored media. As there is no way for the cast receiver to gain direct access to files stored locally on the device, I'm using NanoHTTPD to run a simple webserver, basically just serving a FileInputStream of the contents I require the cast receiver to load.

This would nail down to a simple URL, consisting of the phone's intranet IP address, as well as the port specified in the NanoHTTPD subclass's constructor. However, this doesn't happen to work. Instead, it seems the serving results in an empty stream, and therefore an empty file, while the actual file on the device is proven to be existing and non-empty (it can be read by the app itself).

The NanoHTTTPD subclass:

package de.julianostarek.musicplayer.Server;


import android.util.Log;
import android.widget.Toast;

import java.io.FileInputStream;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;


/**
 * Created by Julian Os on 13.02.2016.
 */
public class LocalServer extends NanoHTTPD {
    public static final String TAG = "LocalServer.class";

    public LocalServer(int port) {
        super(port);
    }

    public LocalServer(String hostname, int port) {
        super(hostname, port);
        Log.e(TAG, hostname + ":" + port);
    }

    @Override
    public Response serve(IHTTPSession session) {
        try {
            return new Response(Response.Status.OK, "audio/flac", session.getInputStream());
        }catch (Exception e) {
            Log.e(TAG, "Serving failed: " + e.toString()); return null; }
    }

}

Solution

  • I had this problem in a previous project. I started with NanoHTTPD too but I can't remember what exactly and why I had to change it to work with a Cast device. However, you can take a look at my version: https://github.com/entertailion/Caster/blob/master/src/com/entertailion/java/caster/HttpServer.java