NanoHttpd 构建android 手机端的HttpServer
16lz
2021-01-24
NanoHttpd是Github上的一个开源项目, 通过下载jar包,新建一个android project, 使用 extends NanoHTTPD 就可以实现一个apk 当WebServer。
示例为显示访问此server的Useragent 和将UA写入文件import fi.iki.elonen.NanoHTTPD;public class UAsetHttpServer extends NanoHTTPD { public UAsetHttpServer() throws IOException { super(8080); } @Override public Response serve(IHTTPSession session) { System.out.println("UAsetHttpServer, method serve start-----"); String msg = "\n"; msg += ""; msg += "\n"; if(session.getUri().equals("/")){ String ua = session.getHeaders().get("user-agent"); System.out.println("UAsetHttpServer, session.getHeaders()-----"+ua); try{ File file = new File("/data/local/tmp/useragent.txt"); FileOutputStream fs = new FileOutputStream(file); OutputStreamWriter ow = new OutputStreamWriter(fs); ow.write(ua); ow.close(); System.out.println("UAsetHttpServer, save useragent to file successfully."); }catch(Exception e){ System.out.println("UAsetHttpServer, save useragent to file error:"+e.getMessage()); } } return new NanoHTTPD.Response(msg); }}
调用的地方:
public class AndroidBrowserUAActivity extends Activity { private UAsetHttpServer server; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onResume() { super.onResume(); try { server = new UAsetHttpServer(); server.start(); } catch (IOException e) { e.printStackTrace(); server = null; } } @Override protected void onDestroy() { super.onDestroy(); if (server != null) { server.stop(); } }}
当以上的Server起来之后,使用地址http://127.0.0.1:8080/就可以访问。
更多相关文章
- 使用jenkins自动化构建Android(安卓)app
- FileObserver的使用
- 一个切换的Widget
- INSTALL_FAILED_TEST_ONLY
- RN: android 显示 gif compile 'com.facebook.fresco:fresco
- 据说年薪30万的Android程序员必须知道事
- Android(安卓)FloatingActionButton: FloatingActionsMenu向下伸
- Android(安卓)的系统属性(SystemProperties)设置分析
- Qt for Android(安卓)使用 手记