Auto.js 网络编程实战:从基础请求到高级数据交互

一、网络请求基础架构

在移动端自动化开发中,网络请求能力是连接本地脚本与云端服务的关键桥梁。Auto.js基于HTTP协议栈实现了完整的网络通信模块,支持同步/异步两种执行模式,开发者可通过http对象直接调用各类请求方法。

1.1 请求生命周期管理

每个网络请求都遵循完整的生命周期:

  1. 请求构造阶段:配置URL、参数、请求头等
  2. 网络传输阶段:建立TCP连接,发送请求报文
  3. 响应处理阶段:解析状态码、响应体、响应头
  4. 资源释放阶段:关闭连接,清理临时数据

建议通过封装统一的请求处理函数来管理生命周期,示例框架如下:

  1. function safeRequest(config) {
  2. try {
  3. const res = http.get(config);
  4. if (res.statusCode !== 200) {
  5. throw new Error(`请求失败: ${res.statusCode}`);
  6. }
  7. return processResponse(res);
  8. } catch (e) {
  9. console.error("请求异常:", e);
  10. return null;
  11. }
  12. }

二、核心请求方法详解

2.1 基础GET请求实现

GET请求是最常用的数据获取方式,适用于查询类接口。关键实现要点:

  • URL编码处理:自动处理中文参数
  • 响应体解析:支持文本/二进制格式
  • 状态码校验:必须检查200以外的状态
  1. // 基础GET请求示例
  2. function fetchWebContent(url) {
  3. const res = http.get(url);
  4. if (res.statusCode === 200) {
  5. const contentLength = res.body.string().length;
  6. console.log(`获取成功,内容长度: ${contentLength}字节`);
  7. return res.body.string();
  8. } else {
  9. throw new Error(`HTTP错误: ${res.statusCode}`);
  10. }
  11. }
  12. // 调用示例
  13. try {
  14. const html = fetchWebContent("https://example.com");
  15. } catch (e) {
  16. toast(e.message);
  17. }

2.2 带参数的查询请求

当需要传递查询参数时,推荐使用buildQuery方法进行参数序列化:

  1. // 构建带参数的GitHub搜索请求
  2. function searchRepositories(query, sortField) {
  3. const baseUrl = "https://api.github.com/search/repositories";
  4. const params = {
  5. q: query,
  6. sort: sortField,
  7. per_page: 10
  8. };
  9. const fullUrl = `${baseUrl}?${http.buildQuery(params)}`;
  10. const res = http.get(fullUrl);
  11. return JSON.parse(res.body.string());
  12. }
  13. // 调用示例
  14. const result = searchRepositories("autojs", "stars");
  15. console.log("搜索结果:", result.items[0].full_name);

2.3 POST请求双模式实现

POST请求支持表单数据和JSON数据两种传输格式:

表单数据提交

  1. // 表单格式提交用户信息
  2. function submitFormData() {
  3. const formData = {
  4. username: "test_user",
  5. device: "autojs_client"
  6. };
  7. const res = http.post("https://httpbin.org/post", formData);
  8. const jsonRes = JSON.parse(res.body.string());
  9. console.log("表单提交结果:", jsonRes.form);
  10. }

JSON数据提交

  1. // JSON格式提交认证信息
  2. function submitJsonData() {
  3. const authData = {
  4. user: "admin",
  5. pwd: "secure_password"
  6. };
  7. const res = http.postJson("https://httpbin.org/post", authData);
  8. const jsonRes = JSON.parse(res.body.string());
  9. console.log("JSON提交结果:", jsonRes.json);
  10. }

2.4 请求头高级定制

通过headers配置可以实现:

  • 模拟浏览器访问
  • 传递认证令牌
  • 指定内容类型
  1. // 带认证头的请求示例
  2. function fetchProtectedResource(token) {
  3. const headers = {
  4. "User-Agent": "AutoJS-Client/1.0",
  5. "Authorization": `Bearer ${token}`,
  6. "Accept-Language": "zh-CN"
  7. };
  8. const res = http.get({
  9. url: "https://api.example.com/data",
  10. headers: headers
  11. });
  12. return JSON.parse(res.body.string());
  13. }

三、文件传输解决方案

3.1 多部分表单上传

文件上传需要使用multipart/form-data格式:

  1. // 上传图片文件示例
  2. function uploadImage(filePath, description) {
  3. const fileStream = open(filePath);
  4. const formData = {
  5. file: fileStream,
  6. desc: description,
  7. timestamp: new Date().getTime()
  8. };
  9. const res = http.postMultipart(
  10. "https://api.example.com/upload",
  11. formData
  12. );
  13. fileStream.close();
  14. return JSON.parse(res.body.string());
  15. }
  16. // 调用示例
  17. uploadImage("/sdcard/test.jpg", "测试图片上传");

3.2 大文件下载策略

对于大文件下载建议:

  1. 检查存储空间是否充足
  2. 使用流式处理避免内存溢出
  3. 添加进度回调机制
  1. // 安全下载文件实现
  2. function downloadFileSafely(url, savePath) {
  3. // 检查存储空间
  4. const stat = files.stat(savePath);
  5. if (stat && stat.size > 100 * 1024 * 1024) {
  6. throw new Error("目标文件已存在且过大");
  7. }
  8. const res = http.get(url);
  9. if (res.statusCode === 200) {
  10. files.writeBytes(savePath, res.body.bytes());
  11. console.log("下载完成,保存至:", savePath);
  12. return true;
  13. }
  14. return false;
  15. }
  16. // 带进度监控的下载实现
  17. function downloadWithProgress(url, savePath, progressCallback) {
  18. // 此处可扩展为分块下载+进度计算
  19. // 实际实现需结合具体业务需求
  20. }

四、异常处理最佳实践

4.1 常见错误类型

错误类型 典型场景 处理策略
网络超时 弱网环境 设置合理超时时间
状态码异常 401未授权/404未找到 跳转登录/提示用户
解析错误 响应体格式不符 添加格式校验逻辑
存储错误 磁盘空间不足 提前检查存储状态

4.2 重试机制实现

  1. // 带重试的请求封装
  2. function requestWithRetry(url, maxRetry = 3) {
  3. let lastError = null;
  4. for (let i = 0; i < maxRetry; i++) {
  5. try {
  6. const res = http.get(url);
  7. if (res.statusCode === 200) {
  8. return res.body.string();
  9. }
  10. lastError = new Error(`HTTP错误: ${res.statusCode}`);
  11. } catch (e) {
  12. lastError = e;
  13. }
  14. // 指数退避重试
  15. sleep(1000 * Math.pow(2, i));
  16. }
  17. throw lastError || new Error("未知错误");
  18. }

五、性能优化建议

  1. 连接复用:对同一主机的多次请求应复用TCP连接
  2. 数据压缩:启用Gzip压缩减少传输量
  3. 缓存策略:合理设置Cache-Control头
  4. 并发控制:避免同时发起过多请求
  1. // 性能优化示例:启用压缩的请求
  2. function optimizedRequest(url) {
  3. const res = http.get({
  4. url: url,
  5. headers: {
  6. "Accept-Encoding": "gzip, deflate"
  7. }
  8. });
  9. // 此处应添加解压缩逻辑(Auto.js默认自动处理)
  10. return res.body.string();
  11. }

通过系统掌握这些网络编程技巧,开发者可以构建出稳定高效的移动端自动化应用,实现与各类云服务的无缝对接。在实际开发中,建议结合具体业务场景建立完善的网络请求中间件,统一处理认证、日志、重试等横切关注点。