HTTPS Client¶
Requires AMC 2.5.2+.
HttpsClient sends HTTP requests from QML to one server. It can present a client certificate that the operator imported into AMC, trust a private CA, and report how the link to the server stands. It never sends a request, a certificate or a header to another server.
Import: import QGroundControl.SecureConnections
The same import gives you LinkState. Secure Connections covers certificates, the LinkState values and the rules that the HTTPS, gRPC and MQTT clients share.
Quick start¶
import QtQuick
import QGroundControl.Plugin
import QGroundControl.SecureConnections
Item {
HttpsClient {
id: dispatch
url: "https://dispatch.example.com/api/v1/"
}
Component.onCompleted: {
const reply = dispatch.request("GET", "work-orders")
reply.finished.connect((status, error) => {
PluginManager.log("MyPlugin: work orders: " + (error !== "" ? error : "HTTP " + status))
})
}
}
You don't have to wait until the client is ready. A request made while it is being set up waits, then goes out.
HttpsClient¶
Properties¶
| Property | Type | Writable | Default | Description |
|---|---|---|---|---|
url |
QUrl |
Yes | "" |
The server, and the path that requests are relative to, e.g. "https://dispatch.example.com/api/v1/". Without a port, https:// uses 443 and http:// 80. Empty leaves the client Off. http:// connects without TLS. |
certificateId |
QString |
Yes | "" |
The id of a certificate the operator imported in Settings → Certificates. Empty presents no client certificate and trusts the system CAs. Ignored without TLS. |
expectedHostName |
QString |
Yes | "" |
The name the server's certificate must carry instead of the host in url, e.g. when you reach the server by IP address. Empty checks the host in url. Ignored without TLS. |
headers |
QVariantMap |
Yes | {} |
Headers sent with every request made from then on, e.g. { "Authorization": "Bearer …" }. See Request headers. |
timeout |
int |
Yes | 10000 |
How long a request that went out may send and receive nothing, in milliseconds. 0 means no limit; a negative value counts as 0. See Limits. |
state |
LinkState |
No | LinkState.Connecting |
How the link to the server stands. See Link state. |
errorString |
QString |
No | "" |
Explains every state except Connecting and Connected, in which it is empty. |
A query or #fragment in url is ignored; pass query parameters with each request. url always counts as a folder, so …/api/v1 and …/api/v1/ are the same.
Methods¶
| Method | Parameters | Returns | Description |
|---|---|---|---|
request(method, path, options) |
QString, QString, QVariantMap |
HttpsReply* |
Sends a request. options may be left out. See Sending requests. |
Signals¶
| Signal | Description |
|---|---|
stateChanged() |
state changed. errorString already explains the new state. |
errorStringChanged() |
errorString changed. |
configurationChanged() |
url, certificateId or expectedHostName changed. |
headersChanged() |
headers changed. |
timeoutChanged() |
timeout changed. |
Sending requests¶
request(method, path, options) returns an HttpsReply straight away. Connect to its finished signal to get the result:
const reply = dispatch.request("GET", "work-orders/17")
reply.finished.connect((status, error) => {
// ...
})
finished is never emitted before request() returns, so connecting right after the call is always in time. A request with bad arguments still returns a reply: it finishes with an error, and nothing is sent.
Method¶
GET, HEAD, POST, PUT, DELETE, PATCH and OPTIONS, in any case. They are sent in upper case. Any other name that is a valid HTTP token is sent exactly as written; anything else makes the request fail.
Path¶
path is relative to url. A path that starts with / starts at the server's root. A full URL is allowed if it is on the same server. With url: "https://dispatch.example.com/api/v1":
path |
Goes to |
|---|---|
"work-orders" |
https://dispatch.example.com/api/v1/work-orders |
"work-orders?status=open" |
https://dispatch.example.com/api/v1/work-orders?status=open |
"" |
https://dispatch.example.com/api/v1/ |
"/health" |
https://dispatch.example.com/health |
"https://dispatch.example.com/files/7" |
https://dispatch.example.com/files/7 |
"https://files.example.com/7" |
Nowhere. The request fails because this is another server; see One server only. |
- Percent-escapes in a path are kept, so encode a
/,?or%that is part of a segment:"work-orders/" + encodeURIComponent(id). Characters a URL can't hold, such as spaces, are encoded for you. A full URL, such as a link the server returned, is sent as written. - The first
?starts the query. A query written into the path is sent as written, so encode it yourself, or use thequeryoption, which encodes for you. - Only a path that starts with
scheme://counts as a full URL, sojobs:searchis an ordinary relative path.
Options¶
options is a JS object. Every key is optional. Any other key makes the request fail.
| Option | Type | Description |
|---|---|---|
query |
object | Query parameters, { name: value }. A value is a string, a number or a boolean, or a list of them; anything else, such as an object, makes the request fail. Names and values are percent-encoded for you. A list value sends the name once per item. Parameters are sorted by name and come after any query written into the path. |
headers |
object | Headers for this request only. They replace the client's headers of the same name, ignoring case. See Request headers. |
body |
object, array, string or ArrayBuffer |
The request body. See Request body. |
timeout |
int | The limit for this request in milliseconds, instead of the client's timeout. 0 means no limit. Leave the key out to use the client's timeout. A negative value, undefined, null or text that isn't a number makes the request fail. Numeric text and booleans are converted: "5000" is 5000 ms, true is 1 ms. |
A query or headers that is not an object, such as an array of pairs or a string like "a=1", makes the request fail. undefined and null count as leaving the key out.
dispatch.request("GET", "work-orders", {
query: { status: "open", tag: ["bridge", "north"] },
timeout: 30000
})
// GET https://dispatch.example.com/api/v1/work-orders?status=open&tag=bridge&tag=north
Request body¶
body |
Sent as | Content-Type |
|---|---|---|
| An object or an array | Compact JSON | application/json |
| A string | UTF-8 text | text/plain; charset=utf-8 |
An ArrayBuffer |
The bytes as they are | application/octet-stream |
Left out, null or undefined |
No body | None |
As with JSON.stringify(), a property whose value is undefined is left out, and an undefined array item is sent as null. A Content-Type in the client's or the request's headers wins over the one in the table. Any other body, such as a number or a boolean, makes the request fail, and so does a body on a HEAD request. A typed array such as Uint8Array is not an ArrayBuffer and goes out as a JSON object; pass its .buffer.
// JSON
dispatch.request("POST", "work-orders", { body: { site: "North bridge", priority: 2 } })
// Text, with your own content type
dispatch.request("POST", "imports", {
body: "id,site\n17,North bridge\n",
headers: { "Content-Type": "text/csv" }
})
Request headers¶
The client's headers go with every request. A request's own headers replace those of the same name, ignoring case.
HttpsClient {
id: dispatch
url: "https://dispatch.example.com/api/v1/"
headers: ({ "Authorization": "Bearer " + root.accessToken, "Accept": "application/json" })
}
function fetchReportCsv() {
// Accept is replaced for this request; Authorization still goes along.
return dispatch.request("GET", "reports/latest", { headers: { "Accept": "text/csv" } })
}
- Names must be valid HTTP header names. A value is a string, a number or a boolean, or a list of them, and must be printable ASCII; anything else, such as an object, makes the request fail. A list value is joined with
", ". - HTTP sets these headers itself, so naming them makes the request fail:
Host,Content-Length,Connection,Transfer-Encoding,TE,Upgrade,Keep-Alive,Proxy-ConnectionandTrailer. - A bad entry in the client's
headersmakes every request fail until you fix it. - A change to
headersapplies to requests made after it, not to those already made.
HttpsReply¶
request() returns an HttpsReply. You can't create one yourself.
Properties¶
Both are read-only and are set when the request finishes.
| Property | Type | Description |
|---|---|---|
status |
int |
The HTTP status code. 0 while the request runs, and when there is no complete answer. |
headers |
QVariantMap |
The response headers, with lower-case names: reply.headers["content-type"]. A header sent more than once arrives as one value. Empty when there is no complete answer. |
Methods¶
| Method | Returns | Description |
|---|---|---|
text() |
QString |
The body as UTF-8 text. |
json() |
QVariant |
The body parsed as JSON: an object, an array, a string, a number, a boolean or null. undefined when the body is not JSON, also when it is empty. |
bytes() |
ArrayBuffer |
The body as raw bytes. |
cancel() |
-- | Ends the request now. finished reports status 0 and the error Cancelled. Does nothing once the request has finished. |
The body is only there when the whole answer arrived, that is when error is empty. json() parses the body once, but every call returns a new copy, so keep the result in a variable. Arrays from json() work like JS arrays, but Array.isArray() returns false for them.
Signals¶
| Signal | Description |
|---|---|
finished(status, error) |
The request is over. status is the same as the property. error is empty when the server's whole answer arrived, whatever the status: a 404 or a 500 comes with an empty error. Otherwise error says why there is no complete answer, e.g. no connection, TLS, the timeout, cancel() or bad arguments. |
Every request finishes exactly once, also when it could not be sent (but see Lifetime).
Check error first, then status
A non-empty error means there is no answer to look at. An empty error means the server answered, and status tells you whether it accepted the request.
Lifetime¶
- The client owns its replies. A running reply is not garbage-collected, so you don't need to keep a reference to it.
- A reply is deleted shortly after
finished. Read what you need in the handler, and drop any reference you kept. - If the client itself is destroyed, for example with the view that declared it, its unfinished requests are dropped without
finished. Declare the client in your data singleton when requests must outlive a view.
To replace a running request, for example a search while the operator types, cancel the old one first:
property var results: []
property var _search: null
function search(text) {
if (root._search) {
root._search.cancel()
}
const reply = dispatch.request("GET", "work-orders", { query: { q: text } })
root._search = reply
reply.finished.connect((status, error) => {
if (root._search === reply) {
root._search = null
}
if (error === "" && status === 200) {
root.results = reply.json()
}
})
}
Link state¶
state tells you how the link to the server stands. Use it for a status display, and each reply's status and error to handle that request. Secure Connections describes each LinkState value.
The client never contacts the server on its own, so the state changes only here:
- A setup sets
Connecting, orOff,ConfigErrororTlsErrorif it fails. - Each request that goes out sets the state when it ends, before its
finishedhandlers run, as the table shows.
| How a request ended | status |
error |
state afterwards |
|---|---|---|---|
| The server answered 401 or 403 | The status | Empty | AuthError |
| The server answered 502, 503 or 504 | The status | Empty | Unreachable |
| The server answered with any other status | The status | Empty | Connected |
| No connection, or it broke off before the whole answer arrived | 0 |
Why | Unreachable |
| Nothing sent or received for as long as the timeout | 0 |
E.g. Nothing was sent or received for 10000 ms. |
Unreachable |
| The system proxy failed or refused the request, e.g. it wants credentials | 0 |
Why | Unreachable |
| The TLS handshake failed | 0 |
Why | TlsError |
| The answer was larger than 64 MiB | 0 |
The response is larger than 64 MiB. |
Connected |
| The server redirected to another server | 0 |
Why | Connected |
| The server kept redirecting | 0 |
The server redirected too many times. |
Connected |
You called cancel() |
0 |
Cancelled. |
Unchanged |
| It never went out: bad arguments, or a full URL on another server or with credentials | 0 |
Why | Unchanged |
After a 401, 403, 502, 503 or 504, errorString reads like The server answered with HTTP status 503.
What a new request does depends on the state:
state |
Why | A new request |
|---|---|---|
Off |
url is empty |
Fails at once, with errorString as its error |
Connecting |
The client is being set up, or no request has ended since the last setup | Waits for the setup if one is running, then goes out |
Connected, Unreachable, AuthError |
How the last request ended | Goes out |
TlsError after a request |
The TLS handshake failed | Goes out |
TlsError after a setup |
The client certificate can't be used | Fails at once. The first request a minute or more later loads the certificate again and waits for it |
TlsError after a refused keychain prompt |
The operator refused the keychain prompt, or the keychain lost the key's passphrase | Fails at once, without a new prompt, until url, certificateId or expectedHostName changes. If another client has loaded the certificate since, the next request loads it again and waits for it |
ConfigError |
url can't work: it is malformed, is not https:// or http://, has no host, has port 0, or holds a user name or password. Or the certificate entry was deleted |
Fails at once |
So don't wait for Connected before you send: the client only gets there by sending. A request that failed is not sent again; send a new one if you need to.
Changing settings¶
- Changing
url,certificateIdorexpectedHostNamesets the client up again. Requests that are running end withThe connection settings changed.Requests that are waiting for the setup, and those you make right after the change, wait for the new setup. Then they go out with the new settings, or fail witherrorStringif the setup fails. Changing several of these at once causes one setup. headersandtimeoutapply to requests made after the change. They don't set the client up again.- Deleting the certificate entry the client uses ends its running requests with
The client certificate was deleted.The state staysConfigErroruntilcertificateIdchanges.
One server only¶
A client talks only to the scheme, host and port of its url. That keeps the client certificate and your headers, such as tokens, with the server they are meant for.
- A
paththat is a full URL must be on the same server and must not contain credentials (user:password@). Otherwise the request fails before anything is sent. - Redirects to the same server are followed. A redirect to another scheme, host or port ends the request:
statusis0anderrornames the other server. So anhttps://client never follows a redirect tohttp://. - Host names are compared ignoring case, and writing the default port makes no difference:
https://DISPATCH.example.com:443/is the same server. - The path in
urlis not a fence:/healthor../v2/work-ordersreach other paths on the same server. - Requests go through the operating system's proxy, if one is set. A proxy can't read
https://traffic, but it can readhttp://traffic.
TLS and certificates¶
The TLS rules are the same for all three clients and are described in Secure Connections. In short:
https://uses TLS 1.2 or later and always checks the server's certificate chain and host name. You can't turn the check off.certificateIdpicks the client certificate to present. If that entry carries CA certificates, the client trusts those instead of the system ones.- Set
expectedHostNamewhen the server's certificate names a different host thanurl, for example when you connect by IP address. - A server can refuse the client certificate after the handshake (TLS 1.3). That request can then end like a network error, with
Unreachablerather thanTlsError. http://sends everything in clear text and presents no certificate;certificateIdandexpectedHostNameare ignored.
Limits¶
| Limit | Value |
|---|---|
| Response size | 64 MiB. A larger answer ends the request with status 0 and the error The response is larger than 64 MiB. |
| Timeout | 10 s by default; set timeout on the client, or the timeout option on a request. A request fails when nothing is sent or received for that long, from when it goes out to the last byte of the answer, redirects included. So a large upload or download that keeps moving is not cut off, while the wait for the server's first answer is. Waiting for the setup doesn't count, e.g. while the system keychain asks the operator for access. |
Error texts are for people
error and errorString are written for the operator and may be translated. Show them or log them, but don't compare them with fixed text. Decide with status, state and whether error is empty.
Examples¶
Fetch JSON¶
A data singleton, MyPluginData.qml, that fetches open inspection work orders every 30 seconds. The server is assumed to answer with { "items": [ … ] }. The singleton logs errorString only when it changes, so a server that stays down is logged once. Nothing is sent while the state is Off or ConfigError, where every request would fail at once.
pragma Singleton
import QtQuick
import QGroundControl.Plugin
import QGroundControl.SecureConnections
Item {
id: root
property var workOrders: []
property string lastError: ""
readonly property int dispatchState: dispatch.state
readonly property string dispatchError: dispatch.errorString
HttpsClient {
id: dispatch
url: "https://dispatch.example.com/api/v1/"
onErrorStringChanged: {
if (dispatch.errorString !== "") {
PluginManager.log("MyPlugin: dispatch: " + dispatch.errorString)
}
}
}
Timer {
interval: 30000
running: true
repeat: true
triggeredOnStart: true
onTriggered: root.refresh()
}
function refresh() {
if (dispatch.state === LinkState.Off || dispatch.state === LinkState.ConfigError) {
return
}
const reply = dispatch.request("GET", "work-orders", { query: { status: "open" } })
reply.finished.connect((status, error) => {
if (error !== "") {
root.lastError = error
return
}
if (status !== 200) {
root.lastError = "HTTP " + status
return
}
const body = reply.json()
if (!body || !body.items) {
root.lastError = "Unexpected response"
return
}
root.workOrders = body.items
root.lastError = ""
})
}
}
Post JSON with a client certificate¶
The operator picks a certificate in your settings panel, which stores its id in certificateId (see CertificateComboBox). reportPosition() sends the active vehicle's position for a delivery, for example when the operator presses a button.
pragma Singleton
import QtQuick
import QtCore
import QGroundControl
import QGroundControl.Plugin
import QGroundControl.SecureConnections
Item {
id: root
property string certificateId: ""
Settings {
category: "MyPlugin"
property alias certificateId: root.certificateId
}
HttpsClient {
id: dispatch
url: "https://dispatch.example.com/api/v1/"
certificateId: root.certificateId
}
function reportPosition(deliveryId) {
const vehicle = QGroundControl.multiVehicleManager.activeVehicle
if (!vehicle || !vehicle.coordinate.isValid) {
return
}
const reply = dispatch.request("POST", "deliveries/" + encodeURIComponent(deliveryId) + "/positions", {
body: {
latitude: vehicle.coordinate.latitude,
longitude: vehicle.coordinate.longitude,
reportedAt: new Date().toISOString()
}
})
reply.finished.connect((status, error) => {
if (error !== "") {
PluginManager.log("MyPlugin: position for " + deliveryId + " not sent: " + error)
} else if (status < 200 || status >= 300) {
PluginManager.log("MyPlugin: position for " + deliveryId + " refused, HTTP " + status + ": " + reply.text())
}
})
}
}
If the certificate can't be used, the request finishes with the reason as its error, and the state is TlsError. If the operator deleted the certificate, the state is ConfigError until they pick another one.
Show the link state¶
A label for an UpperFlyView file, fed by the dispatchState and dispatchError properties of the Fetch JSON singleton.
import QtQuick
import QGroundControl.Controls
import QGroundControl.Palette
import QGroundControl.Plugin
import QGroundControl.SecureConnections
QGCLabel {
text: {
switch (MyPluginData.dispatchState) {
case LinkState.Connected:
return qsTr("Dispatch: online")
case LinkState.Connecting:
return qsTr("Dispatch: connecting")
default:
return qsTr("Dispatch: %1").arg(MyPluginData.dispatchError)
}
}
color: MyPluginData.dispatchState === LinkState.Connected ? qgcPal.colorGreen : qgcPal.colorOrange
}
See also¶
- Secure Connections: certificates,
LinkStateand the rules all clients share. - gRPC Client and MQTT Client: the other two clients.
- Mission Requests: offering work you receive to the operator as a mission.