andserver工具类
package com.rct.ros.util.andserver;
import android.content.Context;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
public class AndServerManager {
private volatile static AndServerManager INSTANCE;
private Server mServer;
private AndServerManager() {
}
public static AndServerManager getInstance() {
if (INSTANCE == null) {
synchronized (AndServerManager.class) {
if (INSTANCE == null) {
INSTANCE = new AndServerManager();
}
}
}
return INSTANCE;
}
public void init(Context context, Server.ServerListener listener) {
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getByName(NetworkUtils.getIPAddress(true)); //获取IP地址
} catch (UnknownHostException e) {
e.printStackTrace();
LogUtils.e(e);
}
mServer = AndServer.webServer(context)
.inetAddress(inetAddress) //地址
.port(8080) //端口
.timeout(10, TimeUnit.SECONDS) //延迟10s
.listener(listener)
.build();
LogUtils.e( "init: " );
}
/**
* Start server.
*/
public void startServer() {
LogUtils.e( "startServer: " );
if (mServer.isRunning()) {
// TODO The server is already up.
} else {
mServer.startup();
}
}
/**
* Stop server.
*/
public void stopServer() {
if (mServer.isRunning()) {
mServer.shutdown();
}
}
}
静态资源配置
package com.rct.ros.util.andserver;
import android.content.Context;
import com.yanzhenjie.andserver.annotation.Config;
import com.yanzhenjie.andserver.framework.config.Multipart;
import com.yanzhenjie.andserver.framework.config.WebConfig;
import com.yanzhenjie.andserver.framework.website.AssetsWebsite;
import java.io.File;
/**
* 静态资源配置
*/
@Config
public class AppConfig implements WebConfig {
@Override
public void onConfig(Context context, Delegate delegate) {
// 增加一个静态网站
delegate.addWebsite(new AssetsWebsite(context, "/static/"));
delegate.addWebsite(new AssetsWebsite(context, "/index/"));
// 自定义配置表单请求和文件上传的条件
delegate.setMultipart(Multipart.newBuilder()
.allFileMaxSize(1024 * 1024 * 20) // 单个请求上传文件总大小
.fileMaxSize(1024 * 1024 * 20) // 单个文件的最大大小
.maxInMemorySize(1024 * 20) // 保存上传文件时buffer大小
.uploadTempDir(new File(context.getCacheDir(), "_server_upload_cache_")) // 文件保存目录
.build());
}
}
controll配置【下面的是静态重定向页面 写接口的话 可以替换为@RestController】
@Controller
public class PageController {
@GetMapping(path = "/")
public String index() {
return "forward:/index.html";
}
}