马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
AndServer官方地点:入门 · GitBook
1.在安卓项目标两个build.grade中添加相关依赖:


2.目次结构:

以我写的顺序去举行理解:
起首创建一个server的管理类:举行初始化,启动,停止利用等
- import android.content.Context;
- import android.util.Log;
- import com.yanzhenjie.andserver.AndServer;
- import com.yanzhenjie.andserver.Server;
- import java.util.concurrent.TimeUnit;
- public class ServerManager {
- private Server mServer;
- private static ServerManager instance;
- private ServerManager(Context context) {
- mServer = AndServer.webServer(context)
- .port(8080)
- .timeout(10, TimeUnit.SECONDS)
- .listener(new Server.ServerListener() {
- @Override
- public void onStarted() {
- // TODO The server started successfully.
- }
- @Override
- public void onStopped() {
- // TODO The server has stopped.
- }
- @Override
- public void onException(Exception e) {
- // TODO An exception occurred while the server was starting.
- }
- })
- .build();
- }
- public static ServerManager getInstance(Context context) {
- if (instance == null) {
- instance = new ServerManager(context);
- }
- return instance;
- }
- public void startServer() {
- if (mServer.isRunning()) {
- // TODO The server is already up.
- } else {
- mServer.startup();
- }
- }
- public void stopServer() {
- if (mServer.isRunning()) {
- mServer.shutdown();
- } else {
- Log.w("AndServer", "The server has not started yet.");
- }
- }
- }
复制代码 在mainactivity中增加启动代码:

其实这个时候运行到真机或者模拟机上时就已经启动了,为了方便测试,增加几个测试接口:
- @RestController
- @RequestMapping(path = "/api")
- public class TestController {
- @GetMapping("/user/get")
- public String test(@RequestParam("id") String id) {
- return "id = " + id;
- }
- }
复制代码 通过浏览器访问安卓设备的IP:8080/api/user/get?id=1会看到浏览器出现id=1的字样
设置web网站的目次:
- @Config
- public class AppConfig implements WebConfig {
- @Override
- public void onConfig(Context context, Delegate delegate) {
- // 增加一个位于assets的web目录的网站
- delegate.addWebsite(new AssetsWebsite(context, "/web/"));
- }
- }
复制代码 如许网页就被映射到assets下的web目次中:
可以通过page去测试:
- @Controller
- public class PageController {
- @GetMapping("/")
- public String index() {
- return "forward:/index.html";
- }
- @GetMapping("/page")
- public String page() {
- return "forward:/page.html";
- }
- }
复制代码 访问根目次:
访问page:
启动已经 |