NetworkRequest QML Type

Transfer data to or from a server. More...

Import Statement: import ArcGIS.AppFramework 1.0

Properties

Signals

Methods

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" }
NameValue
NetworkRequest.UNSENT0
NetworkRequest.ReadyStateUninitialized0
NetworkRequest.OPENED1
NetworkRequest.ReadyStateInitialized1
NetworkRequest.HEADERS_RECEIVED2
NetworkRequest.ReadyStateSending2
NetworkRequest.LOADING3
NetworkRequest.ReadyStateProcessing3
NetworkRequest.DONE4
NetworkRequest.ReadyStateComplete4

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";
                }
        }
}
NameValue
NetworkRequest.StatusCodeContinue100
NetworkRequest.StatusCodeSwitchingProtocols101
NetworkRequest.StatusCodeOK200
NetworkRequest.StatusCodeCreated201
NetworkRequest.StatusCodeAccepted202
NetworkRequest.StatusCodeNonAuthoritativeInformation203
NetworkRequest.StatusCodeNoContent204
NetworkRequest.StatusCodeResetContent205
NetworkRequest.StatusCodePartialContent206
NetworkRequest.StatusCodeMultipleChoices300
NetworkRequest.StatusCodeMovedPermanently301
NetworkRequest.StatusCodeFound302
NetworkRequest.StatusCodeSeeOther303
NetworkRequest.StatusCodeNotModified304
NetworkRequest.StatusCodeUseProxy305
NetworkRequest.StatusCodeTemporaryRedirect307
NetworkRequest.StatusCodeBadRequest400
NetworkRequest.StatusCodeUnauthorized401
NetworkRequest.StatusCodePaymentRequired402
NetworkRequest.StatusCodeForbidden403
NetworkRequest.StatusCodeNotFound404
NetworkRequest.StatusCodeMethodNotAllowed405
NetworkRequest.StatusCodeNotAcceptable406
NetworkRequest.StatusCodeProxyAuthenticationRequired407
NetworkRequest.StatusCodeRequestTimeout408
NetworkRequest.StatusCodeConflict409
NetworkRequest.StatusCodeGone410
NetworkRequest.StatusCodeLengthRequired411
NetworkRequest.StatusCodePreconditionFailed412
NetworkRequest.StatusCodeRequestEntityTooLarge413
NetworkRequest.StatusCodeRequestURITooLong414
NetworkRequest.StatusCodeUnsupportedMediaType415
NetworkRequest.StatusCodeRequestedRangeNotSuitable416
NetworkRequest.StatusCodeExpectationFailed417
NetworkRequest.StatusCodeInternalServerError500
NetworkRequest.StatusCodeNotImplemented501
NetworkRequest.StatusCodeBadGateway502
NetworkRequest.StatusCodeServiceUnavailable503
NetworkRequest.StatusCodeGatewayTimeout504
NetworkRequest.StatusCodeHTTPVersionNotSupported505

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.

NameValue
NetworkRequest.Unknown-1
NetworkRequest.HttpStatusCodeAttribute0
NetworkRequest.HttpReasonPhraseAttribute1
NetworkRequest.RedirectionTargetAttribute2
NetworkRequest.ConnectionEncryptedAttribute3
NetworkRequest.CacheLoadControlAttribute4
NetworkRequest.CacheSaveControlAttribute5
NetworkRequest.SourceIsFromCacheAttribute6
NetworkRequest.DoNotBufferUploadDataAttribute7
NetworkRequest.HttpPipeliningAllowedAttribute8
NetworkRequest.HttpPipeliningWasUsedAttribute9
NetworkRequest.CustomVerbAttribute10
NetworkRequest.CookieLoadControlAttribute11
NetworkRequest.AuthenticationReuseAttribute12
NetworkRequest.CookieSaveControlAttribute13
NetworkRequest.BackgroundRequestAttribute17
NetworkRequest.SpdyAllowedAttribute18
NetworkRequest.SpdyWasUsedAttribute19
NetworkRequest.EmitAllUploadProgressSignalsAttribute20
NetworkRequest.FollowRedirectsAttribute21
NetworkRequest.HTTP2AllowedAttribute22
NetworkRequest.HTTP2WasUsedAttribute23
NetworkRequest.OriginalContentLengthAttribute24
NetworkRequest.RedirectPolicyAttribute25
NetworkRequest.Http2DirectAttribute26
NetworkRequest.User1000
NetworkRequest.UserMax32767

Property Documentation

[read-only] errorCode : int

Returns a code that refers to a description of the error.


[read-only] errorText : string

Returns a human-readable description of the last device error that occurred.


followRedirects : bool

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.


ignoreSslErrors : bool

Boolean value. Default value is false.


method : string

The type of method can be DELETE, GET, HEAD, POST, and PUT.


password : string

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();
        }
}

[read-only] progress : double

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.


readyState : ReadyState

Retrieves the current state of the request operation.


realm : string

Returns the target realm/domain of the network request operation.


[read-only] requestBody : object

This property is currently under review. Please ignore.


[read-only] response : object

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.


[read-only] responseHeaders : object

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":"" }

responsePath : string

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.


[read-only] responseText : string

Retrieves the response body in a string form. This property will not be set if the responsePath property has been set.


responseType : string

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.


[read-only] status : int

Gets the current status of the request. Returns an enumerated value.


[read-only] statusText : string

Returns a string describing the status of the request.


timeout : object


uploadPrefix : string

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


url : url

A string containing the URL to which the request is sent.


user : string

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

error()

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.


sslErrors(object errors)

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.


sslErrorsIgnored(object errors)

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.


timeout()

Note: The corresponding handler is onTimeout.


Method Documentation

abort()

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)

The attribute parameter

The checkResponse parameter

See also setAttribute().


open(string method, url url)

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


open(string method, url url, bool async)

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.


send()

This actions the request to the specified url.

For example,

Component.onCompleted: { networkRequest.send() }

send(object body)

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().


Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.