Android 搭建HTTP服務器--AndServer
概述
AndServer是Android平台的Web Server和Web Framework。 它基於編譯時注解提供了類似SpringMVC的注解和功能,如果您熟悉SpringMVC,則可以非常快速地掌握它。
特性
- 部署靜態網站
- 使用注解開發Http Api
- 全局請求攔截器,使用注解,全局多個
- 全局異常處理器,使用注解,全局唯一
- 全局消息轉換器,使用注解,全局唯一
依賴
添加依賴時請替換下述 {version} 字段為 Github上公開的最新版本號。
dependencies {
implementation 'com.yanzhenjie.andserver:api:{version}'
annotationProcessor 'com.yanzhenjie.andserver:processor:{version}'
}
服務器(Server)
一個WebServer必須要涉及到的點是啟動、停止、網絡地址與端口監聽、連接超時配置、SSL、狀態監聽、Socket的一些優化配置等,AndServer也提供了這些能力。
在AndServer中,只需要啟動服務器即可,其它組件AndServer會自動加載。AndServer的服務器的啟動是在子線程中進行的,因此服務器的啟動成功與否,必須使用監聽器
下面是針對AndServer的服務器管理示例代碼:
public class ServerManager { private static final String TAG = "ServerManager"; private Server mServer; /** * Create server. */ public ServerManager(Context context) { InetAddress inetAddress = null; try { inetAddress = InetAddress.getByName(NetInfo.getIpAddress(context)); //獲取IP地址 Log.d(TAG, "ServerManager: getIpAddress ="+NetInfo.getIpAddress(context)); } catch (UnknownHostException e) { e.printStackTrace(); } mServer = AndServer.serverBuilder(context) .inetAddress(inetAddress) //地址 .port(8080) //端口 .timeout(10, TimeUnit.SECONDS) //延遲10s .listener(new Server.ServerListener() { //監聽Server @Override public void onStarted() { // TODO The server started successfully. Log.d(TAG, "onStarted: "); } @Override public void onStopped() { // TODO The server has stopped. Log.d(TAG, "onStarted: "); } @Override public void onException(Exception e) { Log.e(TAG, "onException: ",e ); // TODO An exception occurred while the server was starting. } }) .build(); } /** * Start server. */ public void startServer() { if (mServer.isRunning()) { // TODO The server is already up. } else { mServer.startup(); } } /** * Stop server. */ public void stopServer() { if (mServer.isRunning()) { mServer.shutdown(); } else { Log.w("AndServer", "The server has not started yet."); } } }
上文中有一段偽代碼,作用是生成一個網絡地址,一般我們都綁定本機在局域網中的IP地址。當然,如果你的設備有一個外網IP,你可以用外網IP來生成一個網絡地址。
InetAddress inetAddress = ...;
例如,使用某個IP生成網絡地址:
InetAddress inetAddress = InetAddress.getByName("192.168.1.11");
例如,使用某個域名生成網絡地址:
InetAddress inetAddress = InetAddress.getByName("www.xxx.com");
服務(Services)
在應用后台啟動一個Services,用於開啟和關閉服務器
Services示例代碼:
public class MyServer extends Service { private static final String TAG = "MyServer"; private ServerManager mServerManager; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate: mServerManager ="+mServerManager); if (mServerManager==null){ mServerManager =new ServerManager(this); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand: mServerManager ="+mServerManager); mServerManager.startServer(); //開啟服務器 return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); if (mServerManager!=null){ mServerManager.stopServer(); //停止服務器 } } }
HTTP API
模擬用戶登錄的Http Api:
@RestController public class UserController { @GetMapping("/user/login") String login(@RequestParam("account") String account, @RequestParam("password") String password) { if("123".equals(account) && "123".equals(password)) { return "Login successful."; } else { return "Login failed."; } } }
上述Http Api的請求地址是http://xxx:8080/user/login
,請求方法是GET
,客戶端需帶上帳號account
參數和密碼password
參數,在帳號和密碼都是123
時,
我們返回給客戶端的數據是Login successful
,否則是Login failed
,默認情況下的響應碼是200。
@RestController public class UserController { @PostMapping("/user/get") User login(@RequestParam("id") String id) { User user = new User(); user.setId(id); user.setName("AndServer"); return user; } }
在RestController中,返回值可以是String、可以是Model對象或者文件等。
你不需要任何注冊或者配置,只需要啟動服務器就可以通過瀏覽器或者測試工具訪問上面的幾個Http Api了。
注:需要在同一個局域網!
源碼地址: https://github.com/yanzhenjie/AndServer
文檔地址: https://www.yanzhenjie.com/AndServer
舊版文檔: https://www.yanzhenjie.com/AndServer/1.x
最后:請留下您的贊!阿里嘎多.