I've written a small Android server using NanoHTTPD. It can serve an HTML file well (web page located at sdcard/www/index.html). Can anybody please help me find out how can I serve an audio or video file instead of an html page using NanoHTTPD? Forgive me if the question seems silly, as I'm new to HTTP! Here is my server side code (I've replaced the webpage path to that of an audio file):
package com.example.zserver;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class MainActivity extends Activity {
private WebServer server;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
server = new WebServer();
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();
}
private class WebServer extends NanoHTTPD {
public WebServer()
{
super(8080);
}
@Override
public Response serve(String uri, Method method,
Map<String, String> header,
Map<String, String> parameters,
Map<String, String> files) {
String answer = "";
try {
// Opening file from SD Card
File root = Environment.getExternalStorageDirectory();
FileReader index = new FileReader(root.getAbsolutePath() +
"/www/music.mp3");
BufferedReader reader = new BufferedReader(index);
String line = "";
while ((line = reader.readLine()) != null) {
answer += line;
}
} catch(IOException ioe) {
Log.w("Httpd", ioe.toString());
}
return new NanoHTTPD.Response(answer);
}
}
}
I've included necessary use-permissions in my code:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Any help would be appreciated. Thanks in advance!
EDIT, Added permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
EDIT1: Canonical way of reading and writing to buffers:
int read;
int n=1;
while((read = dis.read(mybytearray)) != -1){
dos.write(mybytearray, 0, read);}