我使用 NanoHTTPD 编写了一个小型 Android 服务器。它可以很好地提供 HTML 文件(位于 sdcard/www/index.html 的网页)。谁能帮我找出如何使用 NanoHTTPD 提供音频或视频文件而不是 html 页面?如果这个问题看起来很愚蠢,请原谅我,因为我是 HTTP 新手!这是我的服务器端代码(我已将网页路径替换为音频文件的路径):
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);
}
}
}
我在我的代码中包含了必要的使用权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
任何帮助,将不胜感激。提前致谢!
编辑,添加权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
EDIT1:读取和写入缓冲区的规范方式:
int read;
int n=1;
while((read = dis.read(mybytearray)) != -1){
dos.write(mybytearray, 0, read);}