Transfer data to or from a server. More...
Import Statement: | import ArcGIS.AppFramework 1.0 |
Properties
- errorCode : int
- errorText : string
- followRedirects : bool
- headers : NetworkRequestHeaders
- ignoreSslErrors : bool
- method : string
- password : string
- progress : double
- readyState : ReadyState
- realm : string
- requestBody : object
- response : object
- responseHeaders : object
- responsePath : string
- responseText : string
- responseType : string
- status : int
- statusText : string
- timeout : object
- uploadPrefix : string
- url : url
- user : string
Signals
- error()
- sslErrors(object errors)
- sslErrorsIgnored(object errors)
- timeout()
Methods
- abort()
- object attribute(attribute attribute)
- object attribute(attribute attribute, bool checkResponse)
- open(string method, url url)
- open(string method, url url, bool async)
- send()
- send(object body)
- setAttribute(attribute attribute, object value)
Detailed Description
NetworkRequest is used to upload data to a server or download data from a server.
Properties can be used to influence how the data is uploaded (method, headers, followRedirects, ignoreSslErrors, timeout, uploadPrefix), authenticated (user, password, realm) and to monitor or control the downloaded response (readyState, progress, errorCode, errorText, status, statusText, response, responseText, responseType, responsePath).
The following example demonstrates best practice of how to authenticate users with ArcGIS Online or ArcGIS Enterprise.
NetworkRequest { id: generateTokenRequest signal fail(var error) signal success(string token, var expires, bool ssl) method: "POST" uploadPrefix: "file://" onReadyStateChanged: { if (readyState !== NetworkRequest.ReadyStateComplete) { return; } if (errorCode !== 0) { fail(new Error(qsTr("Network Error %1: %2").arg(errorCode).arg(errorText))); return; } if (status !== 200) { fail(new Error(qsTr("Http Status %1: %2").arg(status).arg(statusText))); return; } let obj; try { obj = JSON.parse(responseText); } catch (err) { fail(err); return; } if (obj["error"]) { let error = obj["error"]; if (error["code"] && error["messageCode"] && error["message"]) { fail(qsTr("Portal Error %1: %2: %3").arg(error["code"]).arg(error["messageCode"]).arg(error["message"])); return; } if (error["code"] && error["message"]) { fail(qsTr("Portal Error %1: %2").arg(error["code"]).arg(error["message"])); return; } } if (obj["token"] && obj["expires"]) { success(obj["token"], obj["expires"], obj["ssl"]); return; } if (obj["access_token"] && obj["expires_in"]) { success(obj["access_token"], Date.now() + obj["expires_in"] * 1000, obj["ssl"]); return; } fail(new Error("Unexpected")); } function signIn(portalUrl, username, password) { this.user = ""; this.password = ""; this.realm = ""; this.url = portalUrl + "/sharing/rest/generateToken"; send( { "f" : "json", "username" : username, "password" : password, "referer" : portalUrl } ); } function oauthSignIn(portalUrl, clientId, refreshToken) { this.user = ""; this.password = ""; this.realm = ""; this.url = portalUrl + "/sharing/rest/oauth2/token"; send( { "f" : "json", "client_id" : clientId, "grant_type" : "refresh_token", "refresh_token" : refreshToken } ); } function iwaSignIn(portalUrl, username, password, realm) { this.user = username; this.password = password; this.realm = realm; this.url = portalUrl + "/sharing/rest/generateToken"; send( { "f" : "json" } ); } function pkiSignIn(portalUrl, pkiFileUrl, pkiPassword) { Networking.pkcs12 = Networking.importPkcs12(pkiFileUrl, pkiPassword); if (!Networking.pkcs12) { fail(new Error(qsTr("Unable to decrypt PKCS#12 file"))); return; } this.user = ""; this.password = ""; this.realm = ""; this.url = portalUrl + "/sharing/rest/generateToken"; send( { "f" : "json" } ); } }
The following example demonstrates best practice of how to download an item from ArcGIS Online or ArcGIS Enterprise.
NetworkRequest { id: downloadItemRequest signal fail(var error) signal success() onReadyStateChanged: { if (readyState !== NetworkRequest.ReadyStateComplete) { return; } if (errorCode !== 0) { fail(new Error(qsTr("Network Error %1: %2").arg(errorCode).arg(errorText))); return; } if (status !== 200) { fail(new Error(qsTr("Http Status %1: %2").arg(status).arg(statusText))); return; } success(); } function downloadItem(portalUrl, itemId, token, responsePath) { this.url = portalUrl + "/sharing/rest/content/items/" + itemId + "/data"; this.responsePath = responsePath; send( { token: token } ); } }
The following example demonstrates best practice of how to upload an item to ArcGIS Online or ArcGIS Enterprise. The commented out parameters in the addItem function are included to demonstrate typical expected values.
NetworkRequest { id: addItemRequest method: "POST" signal fail(var error) signal success(var itemId) onReadyStateChanged: { if (readyState !== NetworkRequest.ReadyStateComplete) { return; } if (errorCode !== 0) { fail(new Error(qsTr("Network Error %1: %2").arg(errorCode).arg(errorText))); return; } if (status !== 200) { fail(new Error(qsTr("Http Status %1: %2").arg(status).arg(statusText))); return; } let obj; try { obj = JSON.parse(responseText); } catch (err) { fail(err); return; } if (obj["error"]) { let error = obj["error"]; if (error["code"] && error["messageCode"] && error["message"]) { fail(qsTr("Portal Error %1: %2: %3").arg(error["code"]).arg(error["messageCode"]).arg(error["message"])); return; } if (error["code"] && error["message"]) { fail(qsTr("Portal Error %1: %2").arg(error["code"]).arg(error["message"])); return; } } if (obj["success"] && obj["id"]) { success(obj["id"]); return; } fail(new Error("Unexpected")); } function addItem(portalUrl, owner, params) { // params = { // "title" : "Item Title", // "type" : "Code Sample", // "typeKeywords": "Code Sample", // "description": "Item Description", // "snippet": "Item Snippet" // "thumbnail": "thumbnail.png", // "file": "file.zip", // "token": "0123456789abcdefgh..." // } this.url = portalUrl + "/sharing/rest/content/users/" + owner + "/addItem"; this.uploadPrefix = "file://"; let obj = { "f" : "json" }; for (let key in params) { if (key === "thumbnail" || key === "file") { obj[key] = this.uploadPrefix + params[key]; } else { obj[key] = params[key]; } } send(obj); } }
The following example demonstrates best practice of how to modifiy an item in ArcGIS Online or ArcGIS Enterprise. The commented out parameters in the updateItem function are included to demonstrate typical expected values.
NetworkRequest { id: updateItemRequest method: "POST" signal fail(var error) signal success(var itemId) onReadyStateChanged: { if (readyState !== NetworkRequest.ReadyStateComplete) { return; } if (errorCode !== 0) { fail(new Error(qsTr("Network Error %1: %2").arg(errorCode).arg(errorText))); return; } if (status !== 200) { fail(new Error(qsTr("Http Status %1: %2").arg(status).arg(statusText))); return; } let obj; try { obj = JSON.parse(responseText); } catch (err) { fail(err); return; } if (obj["error"]) { let error = obj["error"]; if (error["code"] && error["messageCode"] && error["message"]) { fail(qsTr("Portal Error %1: %2: %3").arg(error["code"]).arg(error["messageCode"]).arg(error["message"])); return; } if (error["code"] && error["message"]) { fail(qsTr("Portal Error %1: %2").arg(error["code"]).arg(error["message"])); return; } } if (obj["success"] && obj["id"]) { success(obj["id"]); return; } fail(new Error("Unexpected")); } function updateItem(portalUrl, owner, itemId, params) { // params = { // "title" : "Item Title", // "description": "Item Description", // "snippet": "Item Snippet" // "thumbnail": "thumbnail.png", // "file": "file.zip", // "token": "0123456789abcdefgh..." // } this.url = portalUrl + "/sharing/rest/content/users/" + owner + "/items/" + itemId + "/update"; this.uploadPrefix = "file://"; let obj = { "f" : "json" }; for (let key in params) { if (key === "thumbnail" || key === "file") { obj[key] = this.uploadPrefix + params[key]; } else { obj[key] = params[key]; } } send(obj); } }
Enumerations
ReadyState enumeration
The enums provide a description of the current state that is equivalent to the code.
Here is an example use of the Enum values for NetworkRequest.
if ( readyState === NetworkRequest.DONE ) { statusText.text = "Complete" }
Name | Value |
---|---|
NetworkRequest.UNSENT | 0 |
NetworkRequest.ReadyStateUninitialized | 0 |
NetworkRequest.OPENED | 1 |
NetworkRequest.ReadyStateInitialized | 1 |
NetworkRequest.HEADERS_RECEIVED | 2 |
NetworkRequest.ReadyStateSending | 2 |
NetworkRequest.LOADING | 3 |
NetworkRequest.ReadyStateProcessing | 3 |
NetworkRequest.DONE | 4 |
NetworkRequest.ReadyStateComplete | 4 |
StatusCode enumeration
Collection of values that help describe the status of a request.
For example,
onReadyStateChanged: { if ( readyState === NetworkRequest.DONE ) { if (status === NetworkRequest.StatusCodeOK){ app.backgroundColor = "green"; } } }
Name | Value |
---|---|
NetworkRequest.StatusCodeContinue | 100 |
NetworkRequest.StatusCodeSwitchingProtocols | 101 |
NetworkRequest.StatusCodeOK | 200 |
NetworkRequest.StatusCodeCreated | 201 |
NetworkRequest.StatusCodeAccepted | 202 |
NetworkRequest.StatusCodeNonAuthoritativeInformation | 203 |
NetworkRequest.StatusCodeNoContent | 204 |
NetworkRequest.StatusCodeResetContent | 205 |
NetworkRequest.StatusCodePartialContent | 206 |
NetworkRequest.StatusCodeMultipleChoices | 300 |
NetworkRequest.StatusCodeMovedPermanently | 301 |
NetworkRequest.StatusCodeFound | 302 |
NetworkRequest.StatusCodeSeeOther | 303 |
NetworkRequest.StatusCodeNotModified | 304 |
NetworkRequest.StatusCodeUseProxy | 305 |
NetworkRequest.StatusCodeTemporaryRedirect | 307 |
NetworkRequest.StatusCodeBadRequest | 400 |
NetworkRequest.StatusCodeUnauthorized | 401 |
NetworkRequest.StatusCodePaymentRequired | 402 |
NetworkRequest.StatusCodeForbidden | 403 |
NetworkRequest.StatusCodeNotFound | 404 |
NetworkRequest.StatusCodeMethodNotAllowed | 405 |
NetworkRequest.StatusCodeNotAcceptable | 406 |
NetworkRequest.StatusCodeProxyAuthenticationRequired | 407 |
NetworkRequest.StatusCodeRequestTimeout | 408 |
NetworkRequest.StatusCodeConflict | 409 |
NetworkRequest.StatusCodeGone | 410 |
NetworkRequest.StatusCodeLengthRequired | 411 |
NetworkRequest.StatusCodePreconditionFailed | 412 |
NetworkRequest.StatusCodeRequestEntityTooLarge | 413 |
NetworkRequest.StatusCodeRequestURITooLong | 414 |
NetworkRequest.StatusCodeUnsupportedMediaType | 415 |
NetworkRequest.StatusCodeRequestedRangeNotSuitable | 416 |
NetworkRequest.StatusCodeExpectationFailed | 417 |
NetworkRequest.StatusCodeInternalServerError | 500 |
NetworkRequest.StatusCodeNotImplemented | 501 |
NetworkRequest.StatusCodeBadGateway | 502 |
NetworkRequest.StatusCodeServiceUnavailable | 503 |
NetworkRequest.StatusCodeGatewayTimeout | 504 |
NetworkRequest.StatusCodeHTTPVersionNotSupported | 505 |
Attribute enumeration
Enum describing potential attribute codes for network requests. This uses the same values as Qt's network request attributes, with the same behavior. This enum informs the attribute and setAttribute methods.
Name | Value |
---|---|
NetworkRequest.Unknown | -1 |
NetworkRequest.HttpStatusCodeAttribute | 0 |
NetworkRequest.HttpReasonPhraseAttribute | 1 |
NetworkRequest.RedirectionTargetAttribute | 2 |
NetworkRequest.ConnectionEncryptedAttribute | 3 |
NetworkRequest.CacheLoadControlAttribute | 4 |
NetworkRequest.CacheSaveControlAttribute | 5 |
NetworkRequest.SourceIsFromCacheAttribute | 6 |
NetworkRequest.DoNotBufferUploadDataAttribute | 7 |
NetworkRequest.HttpPipeliningAllowedAttribute | 8 |
NetworkRequest.HttpPipeliningWasUsedAttribute | 9 |
NetworkRequest.CustomVerbAttribute | 10 |
NetworkRequest.CookieLoadControlAttribute | 11 |
NetworkRequest.AuthenticationReuseAttribute | 12 |
NetworkRequest.CookieSaveControlAttribute | 13 |
NetworkRequest.BackgroundRequestAttribute | 17 |
NetworkRequest.SpdyAllowedAttribute | 18 |
NetworkRequest.SpdyWasUsedAttribute | 19 |
NetworkRequest.EmitAllUploadProgressSignalsAttribute | 20 |
NetworkRequest.FollowRedirectsAttribute | 21 |
NetworkRequest.HTTP2AllowedAttribute | 22 |
NetworkRequest.HTTP2WasUsedAttribute | 23 |
NetworkRequest.OriginalContentLengthAttribute | 24 |
NetworkRequest.RedirectPolicyAttribute | 25 |
NetworkRequest.Http2DirectAttribute | 26 |
NetworkRequest.User | 1000 |
NetworkRequest.UserMax | 32767 |
Property Documentation
Returns a human-readable description of the last device error that occurred.
Boolean value. Default value is true and allows the request follows the redirects to perform the request.
[read-only] headers : NetworkRequestHeaders |
Returns any valid headers present in the request.
If the host service is configured with HTTP Basic authentication you can leverage NetworkRequest to pass your credentials and get access to the host using the properties "user" and "password". The password property is the corresponding password for the provided user. Please remember these properties are only used in case of host with HTTP Basic Authentication.
App { id: app width: 800 height: 600 NetworkRequest { id: networkRequest url: "http://httpbin.org/basic-auth/user/passwd" followRedirects: true ignoreSslErrors: true responseType: "json" onReadyStateChanged: { if ( readyState === NetworkRequest.DONE ) { jsonText.text = JSON.stringify(response, undefined, 2); } } } Text { id: jsonText clip: true } Component.onCompleted: { networkRequest.user = "user" networkRequest.password = "passwd" networkRequest.send(); } }
Returns the value for the progress of the network request.
This progress value is a combination of the request upload and response download as a decimal value: every value less than 0.5 is when transmitting a request, 0.5 is waiting for the server response, and all values greater than 0.5 up to 1.0 is receiving the response.
Depending on the request being made, this may not progress at a linear rate. For example when downloading a large file, progress will jump quickly from 0 to 0.5 but increase much more slowly afterwards.
The returned object based on the returnType property. By default it will return a string just like returnText, however if you set returnType, the object of your choice will be returned.
For example,
returnType:"json"
would return JSON object
{"name": "Bruce"}
This property will not be set if the responsePath property has been set.
Returns a JSON object header name/value pairs associated with the response. for example,
onReadyStateChanged: { if ( readyState === NetworkRequest.DONE ) {console.log( JSON.stringify(responseHeaders, undefined, 2) ) } }
returns,
{"Cache-Control":"max-age=0,must-revalidate", "Connection":"keep-alive", "Content-Length":"6126", "Content-Type":"text/plain;charset=utf-8", "Date":"Wed, 28 Oct 2015 22:06:00 GMT", "ETag":"5ffaa26f", "Server":"" }
The responsePath property defines a file location for use when downloading a file.
If this property is set, the file will be downloaded directly to the set location. The file will be downloaded in small chunks, minimizing the in-memory footprint. The response and responseText properties will be unset, and the responseType property will be ignored.
If this property is not set, the entire downloaded file will be returned in the device memory. This content will be made available in string form in the responseText property. The response property will contain the downloaded content in the form set by the responseType property. If this property is unset, consider setting the NetworkRequestHeaders to do HTTP range requests to ensure that the downloaded content is always in small chunks.
Retrieves the response body in a string form. This property will not be set if the responsePath property has been set.
Describes the data type of the response associated with the request. This can be set as 'text', 'json', 'base64', or 'binary'. Any other value will be interpreted as 'text'.
This property will be ignored if the responsePath property has been set.
The default value of uploadPrefix is "@" to maintain compatibility with existing 'curl style' code. The uploadPrefix can be set to any string value to resolve possible ambiguities e.g. Unlikely unicode characters, guid etc
If the host service is configured with HTTP Basic authentication you can leverage NetworkRequest to pass your credentials and get access to the host using the properties "user" and "password". The user property implies the username required for the authentication. Please remember these properties are only used in case of host with HTTP Basic Authentication.
App { id: app width: 800 height: 600 NetworkRequest { id: networkRequest url: "http://httpbin.org/basic-auth/user/passwd" followRedirects: true ignoreSslErrors: true responseType: "json" onReadyStateChanged: { if ( readyState === NetworkRequest.DONE ) { jsonText.text = JSON.stringify(response, undefined, 2); } } } Text { id: jsonText clip: true } Component.onCompleted: { networkRequest.user = "user" networkRequest.password = "passwd" networkRequest.send(); } }
Signal Documentation
Indicates all possible error conditions found during the processing of the request. This signal can be used in conjunction with the readyState and status properties to deduce an error. Responses will always report in the order of readyState, error, status.
if ( readyState === NetworkRequest.DONE ) { if (errorCode === 0) { if (status === NetworkRequest.StatusCodeOK){ console.log ( JSON.stringify ( response, undefined, 2 ) ) } } }
Note: The corresponding handler is onError
.
Executes if the ignoreSslErrors property is set to false and then a ssl error occurs. For example,
NetworkRequest { onSslErrors: console.log ("Danger! Danger!") }
Note: The corresponding handler is onSslErrors
.
Executes if the ignoreSslErrors property is set to true and then a ssl error occurs. For example,
NetworkRequest { onSslErrorsIgnored: console.log ("moving on...") }
Note: The corresponding handler is onSslErrorsIgnored
.
Method Documentation
Aborts the operation immediately and close down any network connections still open. Uploads still in progress are also aborted.
Provides a method to cancel a networkRequest operation cleanly.
item { NetworkRequest { id: networkRequest url: "http://appstudio.arcgis.com/images/index/introview.jpg" responsePath: "c:/temp/appstudio.jpg" property url imagePath: AppFramework.resolvedPathUrl(responsePath) onReadyStateChanged: { if ( readyState === NetworkRequest.DONE ) { image.source = imagePath } } onProgressChanged: progressbar.color = "#"+((1<<24)*Math.random()|0).toString(16) } Rectangle { visible: networkRequest.readyState !== NetworkRequest.DONE anchors { top: parent.top left:parent.left } width: parent.width height: 10 color: "lightGrey" Rectangle { id: progressbar height: parent.height width: parent.width * networkRequest.progress } Row { anchors { horizontalCenter: parent.horizontalCenter top: progressbar.bottom; topMargin: 5 } spacing: 20 Text { text: Math.floor(networkRequest.progress * 100) + "%" } Text { text : qsTr("Cancel download") MouseArea{anchors.fill: parent; onClicked: networkRequest.abort()} } } } }
object attribute(attribute attribute) |
Returns the attribute associated with the given attribute code.
The attribute parameter
The attribute code to return.
object attribute(attribute attribute, bool checkResponse) |
Provides options on request-response between a client and server.
This method exists to be similar to the XMLHttpRequest::open() web API method. This is so that when people port their web applications to QML they can switch over to using the NetworkRequest object with minimal changes to their code. This method, presently, offers the ability to set method, url and optionally async properties in an imperative manner. Currently native QML applications merely set method, url and async properties declaratively, so from a QML standpoint, NetworkRequest::open() is not required.
For example,
networkRequest.open("GET", url); networkRequest.send();
The method parameter
HTTP request is "GET" or "POST". Default value is "GET".
The url parameter
For example,
http://sampleserver6.arcgisonline.com/arcgis/rest/services/Wildfire/FeatureServer/0/query?where=1%3D1&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&gdbVersion=&returnDistinctValues=false&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&multipatchOption=&f=html
Provides options on request-response between a client and server, and supply an option to change the sync type.
NetworkRequest::open() method exists so that it is similar with the XMLHttpRequest::open(). This is so that when people port their web applications to QML they can switch over to using the NetworkRequest object with minimal code changes to their code. The NetworkRequest::open() method, presently, offers the ability to set method, url and async properties in an imperative manner. Currently, native QML applications merely set method, url and async properties declaratively, so, from a QML standpoint, NetworkRequest::open() is not required.
For example,
networkRequest.open("GET", url, false);
The method parameter
HTTP request is "GET" or "POST". Default value is "GET".
The url parameter
For example,
http://sampleserver6.arcgisonline.com/arcgis/rest/services/Wildfire/FeatureServer/0/query?where=1%3D1&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&gdbVersion=&returnDistinctValues=false&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&multipatchOption=&f=html
The async parameter
Boolean value, defaults to true which provides an asynchronous call.
This actions the request to the specified url.
For example,
Component.onCompleted: { networkRequest.send() }
Optionally supply a JSON object of properties to assist the request.
For example,
Component.onCompleted: { networkRequest.send({"f":"json"}) }
The body parameter
For example,
{"f":"json"}
setAttribute(attribute attribute, object value) |
Sets the attribute associated with the attribute code to the designated value. If the attribute is already set, the previous value is discarded.
The attribute parameter
The attribute to set to a value.
The value parameter
The value to set the attribute to.
See also attribute().