在 Android 设备上搭建 Web 服务器

作者 : admin 本文共1053个字,预计阅读时间需要3分钟 发布时间: 2024-03-29 共6人阅读

public class Constants {

//服务端接口的端口号
public static final int PORT_SERVER = 1995;

public static final String GET_FILE = “/file”;

public static final String GET_IMAGE = “/image”;

public static final String POST_JSON = “/json”;

}

···
.registerHandler(Constants.GET_FILE, new DownloadFileHandler()) //注册一个文件下载接口
.registerHandler(Constants.GET_IMAGE, new DownloadImageHandler()) //注册一个图片下载接口
.registerHandler(Constants.POST_JSON, new JsonHandler()) //注册一个Post Json接口
···

例如,假设设备的 IP 地址是:192.168.0.101 ,那么在访问 http://192.168.0.101:1995/file 接口时,请求操作就会由 DownloadFileHandler 来处理

下载文件

DownloadFileHandler 实现了 RequestHandler 接口,在 handle 方法中可以获取到请求头,表单数据这些信息,,通过注解声明支持 Get 方式调用,在此直接返回一个文本文件用于下载

/**

  • 作者:leavesC
  • 时间:2018/4/5 16:30
  • 描述:http://github.com/leavesC/AndroidServer
  • http://www.jianshu.com/u/9df45b87cfdf
    */
    public class DownloadFileHandler implements RequestHandler {

@RequestMapping(method = {RequestMethod.GET})
@Override
public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {

File file = createFile();
HttpEntity httpEntity = new FileEntity(file, ContentType.create(getMimeType(file.g

本站无任何商业行为
个人在线分享 » 在 Android 设备上搭建 Web 服务器
E-->