I followed the SO for setting NanoHttpd to serve files from here - How to serve a mp3 file using latest NanoHTTPD 2.3.0 in Android?
This works but I require the use the latest version from Github, because it handles more HTTP methods and is required for project.
I built the jar locally and added and compiled the APK. The web server initializes but every request is returned as Not Found
. Nothing else. There is no log for that as well to see the problem. What is going on?
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.Map;
import android.util.Log;
import org.nanohttpd.protocols.http.NanoHTTPD;
import org.nanohttpd.protocols.http.response.Response;
import org.nanohttpd.protocols.http.response.Status;
import org.nanohttpd.protocols.http.request.Method;
import static org.nanohttpd.protocols.http.response.Response.newChunkedResponse;
public class MainActivity extends AppCompatActivity {
public StackOverflowMp3Server server;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
server = new StackOverflowMp3Server();
try {
server.start();
} catch(IOException ioe) {
Log.w("Httpd", "The server could not start.");
}
Log.w("Httpd", "Web server initialized.");
}
@Override
public void onDestroy()
{
super.onDestroy();
if (server != null)
server.stop();
}
public class StackOverflowMp3Server extends NanoHTTPD {
public StackOverflowMp3Server() {
super(8089);
}
public Response serve(String uri, Method method,
Map<String, String> header, Map<String, String> parameters,
Map<String, String> files) {
String answer = "";
Log.w("HTTPD", uri);
Log.w("HTTPD", parameters.toString());
Log.w("HTTPD", "Method is: "+method.toString());
Log.w("HTTPD", "Header is: "+header.toString());
FileInputStream fis = null;
try {
fis = new FileInputStream("/storage/C67A-18F7/"
+ "/Music/"+uri);
Log.w("HTTPD", uri + " found");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newChunkedResponse(Status.OK, "audio/mpeg", fis);
}
}
}
This same code works in 2.2 till 2.3
But not in the latest, 2.3.2
I get the server started prompt in the adb logcat
03-26 18:18:26.005 15056 15056 W Httpd : Web server initialized.
But all other requests returns Not Found
>$ curl -X GET http://192.168.1.2:8089
Not Found
>$ curl -X GET http://192.168.1.2:8089/demo.mp3
Not Found
I can't find what the problem is with the code?
Your serve()
does not override any method NanoHTTPD is calling. The default implementation returns "404 Not Found".
The signature for serve()
is
protected Response serve(IHTTPSession session)
However it's deprecated. Have a look at IHandler
s as introduced in this commit. (The default handler does still call the deprecated serve()
method.)