我想在 android 应用程序中添加一个 http 服务器。我试过 NanoHTTPD 服务器取自https://github.com/NanoHttpd/nanohttpd
. 所以我可以在我的桌面上将这个 http 服务器作为简单的 java 类运行。并能够从桌面浏览器访问它。
现在我想用 android 应用程序添加这个代码,并在 android 设备中启动这个服务器,并从我的移动设备浏览器访问它。是可能的,是否有任何其他服务器可以与我的 android 应用程序绑定。
我想在 android 应用程序中添加一个 http 服务器。我试过 NanoHTTPD 服务器取自https://github.com/NanoHttpd/nanohttpd
. 所以我可以在我的桌面上将这个 http 服务器作为简单的 java 类运行。并能够从桌面浏览器访问它。
现在我想用 android 应用程序添加这个代码,并在 android 设备中启动这个服务器,并从我的移动设备浏览器访问它。是可能的,是否有任何其他服务器可以与我的 android 应用程序绑定。
Here is my working sample code. It has limitation as activity will removed from memory my server will stop. To remove that I will write a service for this task.
public class MainActivity extends Activity {
private static final int PORT = 8080;
private MyHTTPD server;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
server = new MyHTTPD();
try {
server.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (server != null)
server.stop();
}
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() {
super(8080);
}
@Override public Response serve(IHTTPSession session) {
Method method = session.getMethod();
String uri = session.getUri();
System.out.println(method + " '" + uri + "' ");
String msg = "<html><body><h1>Hello server</h1>\n";
Map<String, String> parms = session.getParms();
if (parms.get("username") == null)
msg +=
"<form action='?' method='get'>\n" +
" <p>Your name: <input type='text' name='username'></p>\n" +
"</form>\n";
else
msg += "<p>Hello, " + parms.get("username") + "!</p>";
msg += "</body></html>\n";
return new NanoHTTPD.Response(msg);
}
}
}
//now access web page using http://127.0.0.1:8080
此代码有效,请尝试
private class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(8080);
}
@Override
public Response serve(String uri, String method, Properties header, Properties parms, Properties files) {
InputStream is = new FileInputStream("/sdcard/1.mp3");
return new NanoHTTPD.Response(HTTP_OK, "audio/mp3", is);
}
}
server = new MyHTTPD();
server.start();
// and now you can use http://localhost:8080 to do something (ex : streaming audio ...)