Skip To Content

NetworkRequest QML Type

Send network requests and receive replies. More...

Import Statement: import ArcGIS.AppFramework 1.0

Properties

Signals

Methods

Detailed Description

Holds the common configuration and settings for the requests it sends. It contains the proxy and cache configuration, as well as the signals related to such issues, and reply signals that can be used to monitor the progress of a network operation.

Item {
    NetworkRequest {
        id: networkRequest
        url: "http://sampleserver6.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer"

        Component.onCompleted: networkRequest.send( { f: "pjson" } );
    }

    TextArea {
        anchors.fill: parent
        text: networkRequest.readyState === NetworkRequest.DONE ? networkRequest.responseText : networkRequest.readyState
    }
}

Here is an example of using the responsePath to load a downloaded image.

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: console.log("progress:", progress)
    }

    Image {
        id: image
        anchors.fill: parent
        fillMode: Image.PreserveAspectFit
    }
}

Here is an example of the errorText property.

Item {
    NetworkRequest {
        id: networkRequest
        url: "http://appstudio.arcgis.com/images/index/introview.jpg2"
        responsePath: "c:/temp/appstudio.jpg"

        property url imagePath: AppFramework.resolvedPathUrl(responsePath)

        onReadyStateChanged: {
            if ( readyState === NetworkRequest.DONE ) {
                image.source = imagePath
            }
        }
        onError: errorTxt.text = errorText + ", " + errorCode
    }

    Text {
        id: errorTxt
    }
}

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

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

[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

ResponsePath is writable property that defines a file location for use when downloading a file.


[read-only] responseText : string

Retrieves the response body as a string.


responseType : string

Describes the data type of the response associated with the request.


[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.


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

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!")
}

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...")
}

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, bool checkResponse)

The attribute parameter

The checkResponse parameter

See also setAttribute().


object attribute(attribute attribute)

The attribute parameter


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.


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


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

send()

This actions the request to the specified url.

For example,

Component.onCompleted: { networkRequest.send() }

setAttribute(attribute attribute, object value)

The attribute parameter

The value parameter

See also attribute().