更新记录

1.0.13(2024-11-09)

  1. 增加获取本机IP地址接口

1.0.12(2024-11-09)

  1. 修复高版本HB只回调一次的兼容性问题
  2. 修复Android的新基座的编译问题
  3. 接口重构已适配将要增加的鸿蒙系统

1.0.11(2024-09-07)

  1. 修复新版本基座iOS json转换问题
查看更多

平台兼容性

Vue2 Vue3
App 快应用 微信小程序 支付宝小程序 百度小程序 字节小程序 QQ小程序
HBuilderX 3.6.8,Android:4.4,iOS:9,HarmonyNext:不确定 × × × × × ×
钉钉小程序 快手小程序 飞书小程序 京东小程序
× × × ×
H5-Safari Android Browser 微信浏览器(Android) QQ浏览器(Android) Chrome IE Edge Firefox PC-Safari
× × × × × × × × ×

前言

HttpServe是Android、iOS搭建APP本地web service的插件

功能

  1. app本地浏览多个静态web网站,支持自定义路径、_www 、_doc、_documents、_downloads等路径
  2. 支持get、post等请求,动态自定义返回数据,数据类型支持json、html、file、text
  3. 支持文件上传下载
  4. 搭建本地服务播放本地hls/m3u8视频
  5. 支持跨域
  6. 支持后台运行,后台运行配置请使用保活插件 https://ext.dcloud.net.cn/plugin?name=wrs-uts-keepalive https://ext.dcloud.net.cn/plugin?id=10450

集成

  1. 拷贝demo下的AndroidManifest.xml到项目根目录,Android启动的时候请求读写权限
  2. 集成插件步骤请参考https://www.cnblogs.com/wenrisheng/p/18323027
  • 注意如果url请求中有+号,请使用%2B来替换,如: url里有个+号: http://192.168.0.100:8888/login/aa+007.json 替换后: http://192.168.0.100:8888/login/aa%2B07.json

接口


import {
    HttpServerGetResourceDir,
    HttpServerGetIPAddress,
    HttpServerGetWIFIIPAddress,
    HttpServerGetMobileIPAddress,
    HttpServerRequestManagerPermission,
    HttpServerIsRunning,
    HttpServerGet,
    HttpServerPost,
    HttpServerPostFormData,
    HttpServerAddAssetsWebsite,
    HttpServerAddWebsite,
    HttpServerStart,
    HttpServerStop,
    HttpServerSendResponse,
    HttpServerSetCustomConentType,
    HttpServerGetFilesDir
} from "@/uni_modules/wrs-uts-httpserver";
  • 启动HttpServer服务

所有的站点、接口等都要在服务启动前添加,服务启动后添加无效


HttpServerStart(parseInt(this.port), (resp) => {
    this.showMsg(JSON.stringify(resp))
    let accessHost = ""
    switch (uni.getSystemInfoSync().platform) {
        // android
        case 'android':
            let ip = HttpServerGetMobileIPAddress()
            accessHost = "http://" + ip + ":" + this.port
            break;
            // ios
        case 'ios':
            accessHost = resp.host
            break;
        default:

            break;
    }

    this.showMsg("访问IP:" + accessHost)
})
  • 停止服务

HttpServerStop(() => {
    this.showMsg("Http Server已停止")
})

场景 1 app本地浏览多个静态web网站或下载某个目录下的文件


//静态站点普通文件夹下的站点
// 访问地址:http://127.0.0.1:8888/loginSys/index.html
let filePath = this.wwwDir + '/static/loginSys'
let urlMatch = "/loginSys/.*?"
HttpServerAddWebsite(urlMatch, filePath, () => {
    // 添加addWebsite完成
});

场景 2 搭建本地服务播放本地hls/m3u8视频

下载m3u8视频可以使用插件https://ext.dcloud.net.cn/plugin?id=19085


// 播放HLS(M3u8)视频
// 播放地址:http://127.0.0.1:8888/video/hls/index.m3u8
let hlsDir = this.wwwDir + '/static/video/hls'
HttpServerAddWebsite("/video/hls/.*?", hlsDir, () => {
    // 添加addWebsite完成
});
  • Get请求

// get请求
// http://127.0.0.1:8888/get
HttpServerGet("/get", (request) => {
    console.log("Get request:" + JSON.stringify(request))
    this.sendJSONResponse(request)
    // ios:
    // {"urlParams":{"name":"wrs"},"url":"http://172.16.11.44:8888/get?name=wrs","method":"GET","headers":{"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36","Upgrade-Insecure-Requests":"1","Accept-Encoding":"gzip, deflate","Connection":"keep-alive","Host":"172.16.11.44:8888","Accept-Language":"zh-CN,zh;q=0.9","Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"},"path":"/get"}
    // android:
    // {"url":"/get","headers":{"accept":"*/*","user-agent":"PostmanRuntime/7.35.0","accept-encoding":"gzip, deflate, br","host":"172.16.11.21:8888","connection":"keep-alive","postman-token":"bd55de40-aae8-47a6-b971-83205df665f7"},"path":"/get","method":"GET","urlParams":{},"requestID":"/get_514aff025303-4c6a-93dc-1affef73c579"}
}, () => {
    // 添加get完成
});

// http://127.0.0.1:8888/getHtml
HttpServerGet("/getHtml", (request) => {
    console.log("Get request:" + JSON.stringify(request))
    this.sendHtmlResponse(request)

}, () => {
    // 添加get完成
});

// http://127.0.0.1:8888/getFile/aa?name=11.jpg
HttpServerGet("/getFile/.*?", (request) => {
    console.log("Get request:" + JSON.stringify(request))
    let name = request.urlParams.name
    if (name == "11.jpg") { // 下载第一个文件
        this.sendFileResponse(request)
    } else { // 下载其他文件
        this.sendFileResponse(request)
    }

    // ios:
    // {"urlParams":{"name":"wrs"},"url":"http://172.16.11.44:8888/get?name=wrs","method":"GET","headers":{"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36","Upgrade-Insecure-Requests":"1","Accept-Encoding":"gzip, deflate","Connection":"keep-alive","Host":"172.16.11.44:8888","Accept-Language":"zh-CN,zh;q=0.9","Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"},"path":"/get"}
}, () => {
    // 添加get完成
});
  • Post请求

// post请求
// http://127.0.0.1:8888/post
HttpServerPost("/post", (request) => {
    console.log("Post request:" + JSON.stringify(request))
    this.sendJSONResponse(request)
}, () => {
    // 添加post完成
});
  • Post请求-FormData

// post请求,body为form-data,支持文件上传,请使用HttpServerPostFormData
// http://127.0.0.1:8888/postFormData
HttpServerPostFormData("/postFormData", this.saveDir, (request) => {
    console.log("Post request:" + JSON.stringify(request))
    // ios:
    // {
    //  "remoteAddress": "192.168.0.103:56803",
    //  "body": {
    //      "file2": {
    //          "fileName": "iOS管控平台需求.md",
    //          "isFile": true,
    //          "path": "/private/var/mobile/Containers/Data/Application/35A6902A-A761-49BA-A189-47E94A284FF0/tmp/460F0EA2-BC98-411B-B26E-8073F3E31210-18698-000005C56A961941"
    //      },
    //      "file1": {
    //          "fileName": "Cache_-6fd6123ad3d21b0b.jpg",
    //          "isFile": true,
    //          "path": "/private/var/mobile/Containers/Data/Application/35A6902A-A761-49BA-A189-47E94A284FF0/tmp/D139A89E-2496-4159-976C-931B732AD5FC-18698-000005C56A7853AD"
    //      }
    //  },
    //  "requestID": "D24938E8-B9CC-4828-A196-A4AA1A5BFB6C",
    //  "urlParams": {},
    //  "url": "fake://host/postFormData",
    //  "localAddress": "192.168.0.107:8888",
    //  "method": "POST",
    //  "headers": {
    //      "Content-Type": "multipart/form-data; boundary=--------------------------426280402340586636078845",
    //      "Content-Length": "126589",
    //      "Postman-Token": "609c5130-59c7-4765-8a14-2b4c9151c6a2"
    //  },
    //  "path": "/postFormData"
    // }

    // android:
    // {
    //  "url": "/postFormData",
    //  "headers": {
    //      "content-type": "multipart/form-data; boundary=--------------------------394845149470249536860519",
    //      "postman-token": "5732d9c3-dba1-4cdd-a22e-fd43fe2c7641",
    //      "content-length": "126589"
    //  },
    //  "path": "/postFormData",
    //  "method": "POST",
    //  "body": {
    //      "file1": {
    //          "isFile": true,
    //          "fileName": "Cache_-6fd6123ad3d21b0b.jpg",
    //          "path": "/storage/emulated/0/Android/data/uni.UNI005DB01/downloads/da9d54c2116d-4c33-85a6-cee589441610.jpg"
    //      },
    //      "file2": {
    //          "isFile": true,
    //          "fileName": "iOS管控平台需求.md",
    //          "path": "/storage/emulated/0/Android/data/uni.UNI005DB01/downloads/1fd5c17959cd-46c1-a662-e9c9a226be17.md"
    //      }
    //  },
    //  "urlParams": {},
    //  "requestID": "/postFormData_60803c973c5a-48c9-bd66-b59250668123"
    // }
    this.sendJSONResponse(request)
}, () => {
    // 添加post完成
});
  • 设置自定义响应体的contentType

// 设置自定义响应体的contentType
HttpServerSetCustomConentType({
    ".wasm": "application/wasm"
})

动态返回给客服端的数据

  • 返回JSON

let requestID = request.requestID
let resp = {
    type: "json", // 返回类型
    value: {  // 返回值,即响应数据
        "name": "张三",
        "info": {
            "age": 12
        },
        teams: [{
            "name": "xxx"
        }]
    },
    headers: { // 返回头
        token: "xxxx-xx"
    }
}
HttpServerSendResponse(requestID, resp)
  • 返回html或text

let requestID = request.requestID
let resp = {
    type: "html", // html或text
    value: '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>你好,我是html</body></html>',
    headers: {
        token: "xxxx-xx"
    }
}
HttpServerSendResponse(requestID, resp)
  • 返回文件,即下载文件

var filePath = plus.io.convertLocalFileSystemURL("_www/static/video/movie.mp4")
let requestID = request.requestID
let resp = {
    type: "file",
    value: filePath,
    headers: {
        token: "xxxx-xx"
    }
}
HttpServerSendResponse(requestID, resp)
  • 获取本机IP地址

# 如果是本手机访问,建议使用127.0.0.1,如果是其他手机或pc访问,可以采用下面ip
let ip = HttpServerGetMobileIPAddress()

隐私、权限声明

1. 本插件需要申请的系统权限列表:

Android: 文件读写权限

2. 本插件采集的数据、发送的服务器地址、以及数据用途说明:

插件不采集任何数据

3. 本插件是否包含广告,如包含需详细说明广告表达方式、展示频率:

使用中有什么不明白的地方,就向插件作者提问吧~ 我要提问