脚本引擎 API
网络请求 API
runtime.network.* 发送 HTTP 请求。支持 GET/POST/PUT/PATCH/DELETE,可自定义 Headers 和超时,支持二进制下载。
概述
发送 HTTP 请求并获取响应文本或二进制数据。所有请求阻塞当前脚本直到完成。超时可通过参数调整,默认为 10 秒。所有请求自动携带持久化 Cookie(由 runtime.cookies 管理),响应 Set-Cookie 也会自动保存。
方法列表
runtime.network.getText(url, connectTimeoutMs?: 10000, readTimeoutMs?: 10000): string— GET 请求返回文本。runtime.network.getTextWithHeaders(url, headers: object, connectTimeoutMs?: 10000, readTimeoutMs?: 10000): string— 带自定义 Headers 的 GET 文本请求。runtime.network.postText(url, body: string, connectTimeoutMs?: 10000, readTimeoutMs?: 10000): string— POST 请求返回文本。runtime.network.getBytes(url, connectTimeoutMs?: 10000, readTimeoutMs?: 10000): string— GET 请求返回 Base64 编码的字节数据(用于下载图片/文件)。runtime.network.getBytesWithHeaders(url, headers: object, connectTimeoutMs?: 10000, readTimeoutMs?: 10000): string— 带自定义 Headers 的二进制下载。runtime.network.request(method, url, headers?: object, body?: string, connectTimeoutMs?: 10000, readTimeoutMs?: 10000): string— 通用 HTTP 请求。method 支持 GET/POST/PUT/PATCH/DELETE。headers 为键值对对象。
调用示例
// 简单 GET 请求
var resp = runtime.network.getText("https://api.example.com/status");
runtime.process.log("响应: " + resp);
var data = JSON.parse(resp);
runtime.process.log("状态: " + data.status);// 下载图片并保存到本地
var imgB64 = runtime.network.getBytes("https://example.com/photo.jpg", 15000, 15000);
if (imgB64) {
runtime.files.writeBytes("/sdcard/Download/photo.jpg", imgB64);
runtime.process.log("图片已保存");
}// 登录并保持 Cookie(所有后续请求自动携带)
runtime.network.postText("https://example.com/login", "user=admin&pass=123");
// Cookie 已自动保存,后续请求自动携带
var data = runtime.network.getText("https://example.com/dashboard");
runtime.process.log("仪表盘: " + data);// 带签名头的请求
var timestamp = Date.now().toString();
var sign = runtime.crypto.md5("secret_key" + timestamp);
var headers = {"X-Timestamp": timestamp, "X-Sign": sign};
var resp = runtime.network.getTextWithHeaders("https://api.example.com/data", headers, 5000, 5000);
runtime.files.write("/sdcard/response.json", resp);注意事项
超时参数范围限制在 1000~60000 毫秒之间。连接超时和读取超时可分别设置。响应文本为原始字符串,JSON 响应需使用 JSON.parse() 解析。headers 参数为 JS 对象,键值均为字符串。Cookie 会跨请求自动持久化,可通过 runtime.cookies 手动管理。二进制响应(getBytes)返回 Base64 字符串,可用 runtime.files.writeBytes() 写入文件。