我正在尝试使用 NanoHTTP 来提供 HTML 文件。然而,NanoHTTP 相对没有文档,而且我是 Android 新手。我的问题是,我在哪里存储 html 文件,以及如何具体地使用 NanoHTTP 提供它。
最佳答案
一个迟到的答案,但可能对其他人有用。
这是一个简单的 hello Web Server,与您所要求的不完全一样,但您可以从这里继续。下面的程序假设你在 SD 卡的根目录下有一个 www
目录,里面有一个文件 index.html
。
主要 Activity Httpd.java
:
package com.inforscience.web;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import java.io.*;
import java.util.*;
public class Httpd extends Activity
{
private WebServer server;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
server = new WebServer();
try {
server.start();
} catch(IOException ioe) {
Log.w("Httpd", "The server could not start.");
}
Log.w("Httpd", "Web server initialized.");
}
// DON'T FORGET to stop the server
@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 {
// Open file from SD Card
File root = Environment.getExternalStorageDirectory();
FileReader index = new FileReader(root.getAbsolutePath() +
"/www/index.html");
BufferedReader reader = new BufferedReader(index);
String line = "";
while ((line = reader.readLine()) != null) {
answer += line;
}
reader.close();
} catch(IOException ioe) {
Log.w("Httpd", ioe.toString());
}
return new NanoHTTPD.Response(answer);
}
}
}
显然 NanoHTTPD
类必须在同一个包中。
您需要在 AndroidManifest.xml
中授予互联网权限。
<uses-permission android:name="android.permission.INTERNET" />
并读取外部存储权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
编辑:要访问服务器,请使用您设备的 IP 打开您的网络浏览器,例如192.168.1.20:8080
.
注意事项:
- 在 Android 2.3 中测试
- 80 端口的使用仅限于 root 用户 (http://www.mail-archive.com/android-developers@googlegroups.com/msg47377.html)。
关于android - 在 Android 中使用 NanoHTTPD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14309256/