 | |  |  | AIWROK软件JSON请求完整示例
- /**
- * AIWROK HTTP请求完整示例
- * 功能:GET/POST请求、超时控制、自动重试、JSON解析
- * 适用:安卓 Rhino ES5 引擎
- */
- importClass(java.net.HttpURLConnection);
- importClass(java.net.URL);
- importClass(java.io.BufferedReader);
- importClass(java.io.InputStreamReader);
- importClass(java.io.OutputStreamWriter);
- // ======================== 工具函数 ========================
- /**
- * 手动构建 JSON(Rhino 环境下 JSON.stringify 可能不可用)
- */
- function toJson(obj) {
- var parts = [];
- for (var key in obj) {
- // Rhino ES5 下不用 hasOwnProperty(Java 包装类型没有这个方法)
- var val = "" + obj[key];
- if (typeof obj[key] === "string" || obj[key] instanceof java.lang.String) {
- val = val.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
- parts.push('"' + key + '":"' + val + '"');
- } else {
- parts.push('"' + key + '":' + val);
- }
- }
- return "{" + parts.join(",") + "}";
- }
- /**
- * 手动解析 JSON(使用 org.json.JSONObject)
- */
- function parseJson(jsonStr) {
- try {
- var jsonObj = new org.json.JSONObject(jsonStr);
- return jsonObj;
- } catch (e) {
- printl("[parseJson] 解析失败: " + e.message);
- return null;
- }
- }
- // ======================== HTTP 客户端 ========================
- /**
- * HTTP GET 请求
- * @param {string} url - 请求地址
- * @param {object} headers - 自定义请求头
- * @param {number} timeout - 超时时间(毫秒)
- * @returns {object} {code, body, headers, success}
- */
- function httpGet(url, headers, timeout) {
- headers = headers || {};
- timeout = timeout || 10000;
- try {
- var conn = new URL(url).openConnection();
- conn.setRequestMethod("GET");
- conn.setConnectTimeout(timeout);
- conn.setReadTimeout(timeout);
- conn.setUseCaches(false);
- // 设置默认 User-Agent
- conn.setRequestProperty("User-Agent", "AIWROK/1.0");
- conn.setRequestProperty("Content-Type", "application/json");
- // 设置自定义请求头
- for (var key in headers) {
- conn.setRequestProperty(key, headers[key]);
- }
- var code = conn.getResponseCode();
- var is = (code >= 200 && code < 300) ? conn.getInputStream() : conn.getErrorStream();
- if (!is) {
- conn.disconnect();
- return { code: code, body: "", success: false };
- }
- var reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
- var sb = new java.lang.StringBuilder();
- var line;
- while ((line = reader.readLine()) != null) {
- sb.append(line);
- }
- reader.close();
- conn.disconnect();
- return { code: code, body: sb.toString(), success: code >= 200 && code < 300 };
- } catch (e) {
- return { code: -1, body: "", success: false, error: e.message };
- }
- }
- /**
- * HTTP POST 请求
- * @param {string} url - 请求地址
- * @param {object} data - POST 数据对象
- * @param {object} headers - 自定义请求头
- * @param {number} timeout - 超时时间(毫秒)
- * @returns {object} {code, body, headers, success}
- */
- function httpPost(url, data, headers, timeout) {
- headers = headers || {};
- timeout = timeout || 10000;
- try {
- var jsonStr = toJson(data);
- var bodyBytes = new java.lang.String(jsonStr).getBytes("UTF-8");
- var conn = new URL(url).openConnection();
- conn.setRequestMethod("POST");
- conn.setDoOutput(true);
- conn.setDoInput(true);
- conn.setConnectTimeout(timeout);
- conn.setReadTimeout(timeout);
- conn.setUseCaches(false);
- conn.setRequestProperty("User-Agent", "AIWROK/1.0");
- conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
- conn.setRequestProperty("Content-Length", "" + bodyBytes.length);
- for (var key in headers) {
- conn.setRequestProperty(key, headers[key]);
- }
- var os = conn.getOutputStream();
- os.write(bodyBytes);
- os.flush();
- os.close();
- var code = conn.getResponseCode();
- var is = (code >= 200 && code < 300) ? conn.getInputStream() : conn.getErrorStream();
- if (!is) {
- conn.disconnect();
- return { code: code, body: "", success: false };
- }
- var reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
- var sb = new java.lang.StringBuilder();
- var line;
- while ((line = reader.readLine()) != null) {
- sb.append(line);
- }
- reader.close();
- conn.disconnect();
- return { code: code, body: sb.toString(), success: code >= 200 && code < 300 };
- } catch (e) {
- return { code: -1, body: "", success: false, error: e.message };
- }
- }
- /**
- * 带重试的请求(自动重试失败的请求)
- */
- function httpGetWithRetry(url, headers, timeout, retryCount) {
- retryCount = retryCount || 3;
- for (var i = 0; i < retryCount; i++) {
- printl("[重试 " + (i + 1) + "/" + retryCount + "] GET " + url);
- var result = httpGet(url, headers, timeout);
- if (result.success) return result;
- sleep.millisecond(1000 * (i + 1)); // 递增等待
- }
- printl("[重试失败] " + url);
- return null;
- }
- // ======================== 演示 ========================
- function demo() {
- printl("╔══════════════════════════════════════════════╗");
- printl("║ AIWROK HTTP请求完整示例 - 演示 ║");
- printl("╚══════════════════════════════════════════════╝");
- sleep.millisecond(600);
- // ---- 演示 1: GET 请求 ----
- printl("\n🌐 [1/5] GET 请求");
- sleep.millisecond(400);
- printl(" 请求: https://httpbin.org/get?name=AIWROK&version=1.0");
- var getStart = new Date().getTime();
- var getResult = httpGet("https://httpbin.org/get?name=AIWROK&version=1.0");
- var getCost = new Date().getTime() - getStart;
- printl(" 状态码: " + getResult.code);
- sleep.millisecond(150);
- printl(" 成功: " + getResult.success + " (用时 " + getCost + "ms)");
- sleep.millisecond(150);
- if (getResult.body) {
- printl(" 响应: " + getResult.body.substring(0, Math.min(180, getResult.body.length())) + "...");
- }
- sleep.millisecond(1200);
- // ---- 演示 2: POST 请求 ----
- printl("\n📤 [2/5] POST 请求");
- sleep.millisecond(400);
- var postData = { name: "AIWROK", type: "automation", version: "1.0" };
- printl(" 提交数据: " + toJson(postData));
- var postStart = new Date().getTime();
- var postResult = httpPost("https://httpbin.org/post", postData);
- var postCost = new Date().getTime() - postStart;
- printl(" 状态码: " + postResult.code);
- sleep.millisecond(150);
- printl(" 成功: " + postResult.success + " (用时 " + postCost + "ms)");
- sleep.millisecond(150);
- if (postResult.body) {
- printl(" 响应: " + postResult.body.substring(0, Math.min(180, postResult.body.length())) + "...");
- }
- sleep.millisecond(1200);
- // ---- 演示 3: 带自定义请求头 ----
- printl("\n🏷️ [3/5] 带自定义请求头");
- sleep.millisecond(400);
- var customHeaders = { "Authorization": "Bearer test-token-12345", "X-Custom-Header": "my-custom-value" };
- printl(" 请求头: Authorization + X-Custom-Header");
- var headerStart = new Date().getTime();
- var headerResult = httpGet("https://httpbin.org/headers", customHeaders);
- var headerCost = new Date().getTime() - headerStart;
- printl(" 状态码: " + headerResult.code + " (用时 " + headerCost + "ms)");
- sleep.millisecond(1200);
- // ---- 演示 4: 错误请求处理 ----
- printl("\n⚠️ [4/5] 错误请求处理");
- sleep.millisecond(400);
- printl(" 请求一个不存在的页面...");
- var errorStart = new Date().getTime();
- var errorResult = httpGet("https://httpbin.org/status/404");
- var errorCost = new Date().getTime() - errorStart;
- printl(" 状态码: " + errorResult.code);
- sleep.millisecond(150);
- printl(" 成功: " + errorResult.success + " (用时 " + errorCost + "ms)");
- sleep.millisecond(1200);
- // ---- 演示 5: 超时控制 ----
- printl("\n⏱️ [5/5] 超时控制 (3秒)");
- sleep.millisecond(400);
- printl(" 请求会延迟 5 秒的接口,超时设置 3 秒...");
- var timeoutStart = new Date().getTime();
- var timeoutResult = httpGet("https://httpbin.org/delay/5", null, 3000);
- var timeoutCost = new Date().getTime() - timeoutStart;
- printl(" 用时: " + timeoutCost + " ms");
- sleep.millisecond(150);
- if (timeoutResult && timeoutResult.success) {
- printl(" ✓ 请求成功 状态码: " + timeoutResult.code);
- } else if (timeoutResult && timeoutResult.code === -1 && timeoutCost >= 3000) {
- printl(" ⏱️ 触发超时(预期行为) 状态码: -1");
- } else {
- printl(" ✗ 请求失败 状态码: " + (timeoutResult ? timeoutResult.code : "-1"));
- }
- sleep.millisecond(600);
- printl("\n╔══════════════════════════════════════════════╗");
- printl("║ 全部演示完成! ║");
- printl("╚══════════════════════════════════════════════╝");
- }
- demo();
复制代码
| |  | |  |
|