http.req()

http.req(url, payload, timeout, encrypt) → { err, code, payload }

Sends an HTTP request; a non-empty payload is sent as a POST body.

Performs an HTTP request and returns the response. Passing a payload string sends a POST with that body; an empty string "" performs a plain GET-style request.

Check res.err === 0 and res.code === 200 before trusting the response, then parse JSON payloads with JSON.parse(res.payload).

Arguments

NameTypeRequiredDefaultDescription
url string yes Target URL, e.g. "http://172.16.220.39/app/abc".
payload string yes POST body. Build with string(obj). Use "" for no payload.
timeout number (ms) yes Request timeout in milliseconds.
encrypt boolean yes Enable AES end-to-end encryption of the payload (key from setEnv("http.aesKey", …)).

Returns

object { err, code, payload } — err 0 and code 200 indicate success; payload is the response body text.

Example

let request = { msg: "hello from client", epoch: datetime().epoch };

let res = http.req("http://172.16.220.39/app/abc",
                   string(request), // POST payload
                   1000,            // timeout ms
                   false);          // no encryption

if(res.err === 0 && res.code === 200){
  let payload = JSON.parse(res.payload);
  print("Remote Q5 Battery Voltage", payload.batteryVoltage);
} else {
  print("Error reading data from remote Q5:", string(res));
}