在Android中使用NanoHTTPD [英] Using NanoHTTPD in Android
问题描述
我正在尝试使用NanoHTTP来提供HTML文件。但是,NanoHTTP是相对没有记录的,而我是Android的新手。我的问题是,我在哪里存储html文件,以及我如何具体可以使用NanoHTTP来服务。
I am trying to use NanoHTTP to serve up an HTML file. However, NanoHTTP is relatively un-documented, and I am new to Android. My question is, where do I store the html file, and how specifically can I serve it up using NanoHTTP.
推荐答案
答案可能对他人有用。
A late answer but may be useful to others.
这是一个简单的hello Web Server,不完全符合您的要求,但您可以从这里继续。以下程序假定您在SD卡的根目录中有一个 www
目录,里面有一个文件 index.html
。
Here is a simple hello Web Server, not exactly what you ask, but you can continue from here. The following program supposes you have a www
directory in the root of the SD Card and a file index.html
inside.
主要活动 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
类必须在同一个包中。
Obviously the NanoHTTPD
class must be in the same package.
您需要在中授予互联网权限AndroidManifest.xml
。
<uses-permission android:name="android.permission.INTERNET" />
并阅读外部存储权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
编辑:要打开您的Web浏览器,您的设备,例如 192.168.1.20:8080
。
To access the server open you web browser with the IP of your device, e.g. 192.168.1.20:8080
.
注意:
- 在Android 2.3中测试
- 使用端口80仅限于root用户( http://www.mail-archive.com/android-developers@googlegroups.com/msg47377。 html )。
- Tested in Android 2.3
- The use of port 80 is restricted to the root user(http://www.mail-archive.com/android-developers@googlegroups.com/msg47377.html).
这篇关于在Android中使用NanoHTTPD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!