Network Functions
Overview
- Network module functions handle HTTP requests
- The network module uses the
httpprefix, e.g.http.downloadFile()
http.request Universal Request Function
- Universal HTTP request
- @param param map parameter with the following fields:
- url: string, request URL
- timeout: integer milliseconds, timeout duration
- method: string — POST, GET, or PUT
- proxy: proxy address as a map with host and port, e.g.
{"host":"11","port":111} - followRedirects: whether to follow redirects — true or false
- requestBody: request body; use a JSON string for JSON payloads
- userAgent: string, HTTP User-Agent
- ignoreContentType: whether to ignore content type — true or false
- ignoreHttpErrors: whether to ignore HTTP errors — true or false
- maxBodySize: integer, maximum HTTP body size
- referrer: string, request referrer
- header: HTTP request headers as a map, e.g.
{"UA":"test"} - cookie: HTTP request cookies as a map, e.g.
{"a":1} - data: HTTP POST data as a map, e.g.
{"a":1} - file: files to upload as a collection, e.g.
[{"key":"a1","fileName":"a.txt","filePath":"D:/"},{"key":"a1","fileName":"a.jpg","filePath":"D:/","contentType":"image/jpg"}]
- contentType is optional
- responseCharset: string, force response content charset
- @return Response object or null
function main() { http_request();}
function http_request() { //url:string //timeout:int ms //method: post ,get //proxy: {"host":"11","port":111} //followRedirects:true false //requestBody: string //userAgent:string //ignoreContentType:true false //ignoreHttpErrors:true false //maxBodySize : int //referrer:string //header:{"UA":"test"} //cookie:{"a":1} //data:{"a":1} //file:[{}] //responseCharset: string let md = utils.dataMd5("12345"); let md2 = utils.fileMd5("D:/sb.png"); let url = "http://192.168.0.5:8081/api/request"; let proxy = {"host": "192.168.0.5", "port": "100"}; let userAgent = "xxx"; let followRedirects = false; let requestBody = JSON.stringify({"A": 111}); let ignoreContentType = true; let ignoreHttpErrors = true; let referrer = "xxx"; let header = { "Content-Type": " application/json; charset=UTF-8", "User-Agent": "from test", "ddd": md, "dd2": md2, "imei": device.getDeviceId() }; let cookie = { "cookie1": "tst1", "cookie2": "tst2" }; let data = { "a1": "aaa", "pwd2": md, "md2": md2 }; let file = [ { "key": "file", "fileName": "f.png", "filePath": "D:/sb.png" }, { "key": "file", "fileName": "f2.png", "filePath": "D:/sde.png", "contentType": "image/png" } ]; let params = { "url": url, "method": "POST", "userAgent": userAgent, "referrer": "baidu.com", "cookie": cookie, "data": data, "file": file }; let x = http.request(params); if (x) { logd("header=> " + JSON.stringify(x.header)); logd("cookie=> " + JSON.stringify(x.cookie)); logd("statusCode=> " + x.statusCode); logd("statusMessage=> " + x.statusMessage); logd("charset=> " + x.charset); logd("contentType=> " + x.contentType); logd("body=> " + x.body); } else { loge("No result"); }}
main();http.requestEx Universal Request Function (Extended)
- Universal HTTP request
- @param param map parameter with the following fields:
- url: string, request URL
- timeout: integer milliseconds, timeout duration
- method: string — POST, GET, or PUT
- proxy: proxy address as a map with host and port, e.g.
{"host":"11","port":111} - followRedirects: whether to follow redirects — true or false
- requestBody: request body; use a JSON string for JSON payloads
- userAgent: string, HTTP User-Agent
- ignoreContentType: whether to ignore content type — true or false
- ignoreHttpErrors: whether to ignore HTTP errors — true or false
- maxBodySize: integer, maximum HTTP body size
- referrer: string, request referrer
- header: HTTP request headers as a map, e.g.
{"UA":"test"} - cookie: HTTP request cookies as a map, e.g.
{"a":1} - data: HTTP POST data as a map, e.g.
{"a":1} - file: files to upload as a collection, e.g.
[{"key":"a1","fileName":"a.txt","filePath":"D:/"},{"key":"a1","fileName":"a.jpg","filePath":"D:/","contentType":"image/jpg"}]
- contentType is optional
- responseCharset: string, force response content charset
- @return Response object or null
function main() { http_request();}
function http_request() { //url:string //timeout:int ms //method: post ,get //proxy: {"host":"11","port":111} //followRedirects:true false //requestBody: string //userAgent:string //ignoreContentType:true false //ignoreHttpErrors:true false //maxBodySize : int //referrer:string //header:{"UA":"test"} //cookie:{"a":1} //data:{"a":1} //file:[{}] //responseCharset: string let md = utils.dataMd5("12345"); let md2 = utils.fileMd5("D:/sb.png"); let url = "http://192.168.0.5:8081/api/request"; let proxy = {"host": "192.168.0.5", "port": "100"}; let userAgent = "xxx"; let followRedirects = false; let requestBody = JSON.stringify({"A": 111}); let ignoreContentType = true; let ignoreHttpErrors = true; let referrer = "xxx"; let header = { "Content-Type": " application/json; charset=UTF-8", "User-Agent": "from test", "ddd": md, "dd2": md2, "imei": device.getDeviceId() }; let cookie = { "cookie1": "tst1", "cookie2": "tst2" }; let data = { "a1": "aaa", "pwd2": md, "md2": md2 }; let file = [ { "key": "file", "fileName": "f.png", "filePath": "D:/sb.png" }, { "key": "file", "fileName": "f2.png", "filePath": "D:/sde.png", "contentType": "image/png" } ]; let params = { "url": url, "method": "POST", "userAgent": userAgent, "referrer": "baidu.com", "cookie": cookie, "data": data, "file": file }; let x = http.requestEx(params); if (x) { logd("header=> " + x.header); // Direct access logd("header=> " + x.header["Location"]); for (let d in x.header) { logd("header key " + d + " " + x.header[d]); } logd("cookie=> " + x.cookie); for (let d in x.cookie) { logd("cookie key " + d + " " + x.cookie[d]); } logd("cookie=> " + x.cookie["aa"]); logd("statusCode=> " + x.statusCode); logd("statusMessage=> " + x.statusMessage); logd("charset=> " + x.charset); logd("contentType=> " + x.contentType); logd("body=> " + x.body); } else { loge("No result"); }}
main();http.downloadFile Download File
- Download a remote file locally; supports resumable downloads
- @param remoteUrl remote file URL
- @param file local file path to save to
- @param timeout download timeout in milliseconds
- @param headers header map, e.g.
{"a":"11"} - @return true on success, false on failure
function main() { let url = "https://imtt.dd.qq.com/16891/apk/DF4FD15AF9A9B51BA74D2710CF738EEF.apk?fsname=com.ishugui_3.9.2.3068_3923068.apk&csr=1bbd"; let x = http.downloadFile(url, "D:/ss.apk", 10 * 1000, {"User-Agent": "test"}); logd("download result-> " + x);}
main();http.downloadFileDefault Download File
- Download a remote file locally with resumable downloads; default timeout is 30 seconds
- @param remoteUrl remote file URL
- @param file local file path to save to
- @param headers header map, e.g.
{"a":"11"} - @return true on success, false on failure
function main() { let url = "https://imtt.dd.qq.com/16891/apk/DF4FD15AF9A9B51BA74D2710CF738EEF.apk?fsname=com.ishugui_3.9.2.3068_3923068.apk&csr=1bbd"; let x = http.downloadFileDefault(url, "D:/ss.apk", {"User-Agent": "test"}); logd("download result-> " + x);}
main();http.httpGetDefault GET Request
- HTTP GET request
- @param url request URL
- @param timeout timeout in milliseconds
- @param headers header map, e.g.
{"a":"11"} - @return string response body
function main() { let url = "http://192.168.0.5:8081/api/httpGet?a=1"; let x = http.httpGetDefault(url, 10 * 1000, {"User-Agent": "test"}); logd(" result-> " + x); loge("result -> " + x);}
main();http.httpGet GET Request
- HTTP GET request
- @param url request URL
- @param params parameter map, e.g.
{"a":"11"}or a plain string - @param timeout timeout in milliseconds
- @param headers header map, e.g.
{"a":"11"} - @return string response body
function main() { let url = "http://192.168.0.5:8081/api/httpGet?a=1"; let pa = {"b": "22"}; let x = http.httpGet(url, pa, 10 * 1000, {"User-Agent": "test"}); logd(" result-> " + x); loge("result -> " + x);}
main();http.httpPost POST Request
- HTTP POST request
- @param url request URL
- @param params parameters, e.g.
{"a":"11"}or a plain string - @param files files to upload, e.g.
{"file1":"D:/1.png"} - @param timeout timeout in milliseconds
- @param headers header map, e.g.
{"a":"11"} - @return string response body
function main() { // Request without files let url = "http://192.168.0.5:8081/api/httpPost"; let pa = {"b": "我是b的值"}; let x = http.httpPost(url, pa, null, 10 * 1000, {"User-Agent": "test"}); logd(" result-> " + x); loge("result -> " + x);}
main();function main() { // Request with file upload let url = "http://192.168.0.5:8081/api/httpPost"; let pa = {"b": "我是b的值"}; let files = {"file1": "D:/p.json", "file2": "D:/z.xml"}; let x = http.httpPost(url, pa, files, 10 * 1000, {"User-Agent": "test"}); logd(" result-> " + x); loge("result -> " + x);}
main();http.postJSON Send JSON
- HTTP POST JSON data
- @param url request URL
- @param json JSON data
- @param timeout timeout in milliseconds
- @param headers header map, e.g.
{"a":"11"} - @return string response body
function main() { let url = "http://192.168.0.5:8081/api/postJSON"; let pa = {"b": "我是b的值"}; let x = http.postJSON(url, pa, 10 * 1000, {"User-Agent": "test"}); logd(" result-> " + x); loge("result -> " + x);}
main();http.newWebsocket WebSocket Communication
- Create a WebSocket connection
- @param url WebSocket URL to connect to
- @param header header map
- @param type library type — 1 = okhttp3, 2 = javawebsocket
- @return
{@link WebSocket}WebSocket object
function main() { let result = []; // Create a new WebSocket connection let ws = http.newWebsocket("ws://192.168.1.76:8081/websocket/device/call?deviceNo=111", null, 2); // Connection parameters when type=1 ws.setCallTimeout(5); ws.setReadTimeout(5); ws.setWriteTimeout(5); // Heartbeat: recommended 0 because some servers do not support ping ws.setPingInterval(0)
// Heartbeat timeout when type=2 ws.setConnectionLostTimeout(5) // Set listener for connection open ws.onOpen(function (ws1, code, msg) { logi("onOpen code " + code + " msg:" + msg); }) // Set text message listener ws.onText(function (ws1, text) { logi(" onText " + text); }) // Set close listener ws.onClose(function (ws1, code, reason) { logi(" onClose " + code + " reason : " + reason + " remote:"); }) ws.onError(function (ws1, msg) { logi(" onError " + msg); result[0] = "error"; }) // bytes is a Java byte array object ws.onBinary(function (ws1, bytes) { // Convert to Java string logi(" onBinary " + new java.lang.String(bytes)); })
// Start connection (blocking) let r = ws.connect(10000); // Enable auto reconnect ws.setAutoReconnect(true); logd("connect {} rr = {}", result[0], r);
while (true) { logd("isconnect " + ws.isConnected()); sleep(1000) if (ws.isConnected()) { b = ws.sendText("new Date-> " + new Date()) logd("send => " + b); sleep(1000) // Convert Java string to bytes ws.sendBinary(new java.lang.String("test").getBytes()); } else { // Reset connection // let reset = ws.reset(); // logd("reset {}",reset) // if (reset) { // logd("Reconnecting..."); // let rc = ws.connect(10000); // logd("Reconnect--> "+rc); // } } } logd("isClosed " + ws.isClosed()) sleep(1000) // Close connection ws.close();}
main();WebSocket Object Methods
connect Synchronous Connection
- Start synchronous connection
- See example
reset Reset Connection
- Reset connection
- @return
{bool}true on success, false on failure - See example
isClosed Check Whether Closed
- Check whether the connection is closed
- @return true if closed, false if not closed
- See example
isConnected Check Whether Connected
- Check whether the connection is established
- @return true if connected, false if not connected
- See example
close Close Connection
- Close the connection
- See example
sendText Send Text
- Send a text message
- @param text text message
- See example
sendBinary Send Binary
- Send binary data
- @param bin Java byte array object
- See example
onOpen Open Callback
- Callback when the connection opens
- @param callback callback function
- See example
onText Text Callback
- Callback when a text message is received
- @param callback callback function
- See example
onClose Close Callback
- Callback when the connection closes
- @param callback callback function
- See example
onError Error Callback
- Callback when an error occurs
- @param callback callback function
- See example
onBinary Binary Message Callback
- Callback when binary data is received
- @param callback callback function
- See example
setReadTimeout Set Read Timeout
- Use when WebSocket library type = 1
- Set read timeout
- @param timeout timeout in seconds
- See example
setWriteTimeout Set Write Timeout
-
Use when WebSocket library type = 1
-
Set write timeout
-
@param timeout timeout in seconds
-
See example
setPingInterval Set Ping Interval
- Use when WebSocket library type = 1
- Set heartbeat timeout
- @param timeout timeout in seconds
- See example
setConnectionLostTimeout Set Connection Lost Timeout
- Use when WebSocket library type = 2
- Set heartbeat timeout
- @param timeout timeout in seconds
- See example
setAutoReconnect Enable Auto Reconnect
- Enable auto reconnect
- See example