HttpRequest

Allows to implement networking features based on the SuperAgent library from VisionMedia. More...

Import Statement: import VPlayApps 1.0
Since: V-Play 2.18.1

Properties

Methods

  • void clearCookies()
  • void config(var options)
  • var del(string url, var callback)
  • var get(string url, var data, var callback)
  • var head(string url, var data, var callback)
  • var patch(string url, var data, var callback)
  • var post(string url, var data, var callback)
  • var put(string url, var data, var callback)

Detailed Description

The V-Play HttpRequest type integrates DuperAgent, a QML clone of the fantastic SuperAgent library from VisionMedia. The library is implemented in Qt/C++ and designed as an alternative to QML's builtin implementation of XmlHttpRequest.

The component is available as a singleton item and usable from all QML components that import V-Play via import VPlayApps 1.0.

Features

  • Modern API in comparison to XmlHttpRequest
  • Support for multipart/form uploads
  • Automatic parsing of response bodies with known content-types
  • Built-in persistent cookie jar
  • Promise API
  • Secure connection (SSL/TLS) API
  • Network activity indicator
  • Image utilities

The currently used Duperagent version is v1.5.0.

Example Usage

The QML API is almost identical to the JS API of SuperAgent. See the SuperAgent documentation for more API examples.

The following functions are not yet available with the DuperAgent QML port:

  • withCredentials: CORS - Not implemented
  • buffer: Response body buffering is not yet implemented
  • pipe: Piping to streams is not supported

Get Request

Use the HttpRequest::get() method to create a new request object. The returned object then allows to specify additional request settings or send the request. For example, use the timeout function to specify the maximum request timeout. With a call of the then or end function you can send the request and handle the result.

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   Component.onCompleted: {
     HttpRequest
       .get("http://httpbin.org/get")
       .timeout(5000)
       .then(function(res) {
         console.log(res.status);
         console.log(JSON.stringify(res.header, null, 4));
         console.log(JSON.stringify(res.body, null, 4));
       })
       .catch(function(err) {
         console.log(err.message)
         console.log(err.response)
       });
   }
 }

This is how the same code looks like using the end() function:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   Component.onCompleted: {
     HttpRequest
       .get("http://httpbin.org/get")
       .timeout(5000)
       .end(function(err, res) {
         if(res.ok) {
           console.log(res.status);
           console.log(JSON.stringify(res.header, null, 4));
           console.log(JSON.stringify(res.body, null, 4));
         }
         else {
           console.log(err.message)
           console.log(err.response)
         }
       });
   }
 }

DELETE, HEAD, PATCH, POST, and PUT requests are also available with a simple change of the method name.

Post Request

A typical JSON POST request might look a little like the following, where we set the Content-Type header field appropriately, and "write" some data, in this case just a JSON string:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   Component.onCompleted: {
     HttpRequest
       .post("https://jsonplaceholder.typicode.com/posts")
       .set('Content-Type', 'application/json')
       .send({ title: "post title", body: "post body" })
       .then(function(res) {
         console.log(res.status);
         console.log(JSON.stringify(res.header, null, 4));
         console.log(JSON.stringify(res.body, null, 4));
       })
       .catch(function(err) {
         console.log(err.message)
         console.log(err.response)
       });
   }
 }

Since JSON is undoubtedly the most common, it's the default Content-Type setting. You can also split the data into multiple send() calls:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   Component.onCompleted: {
     HttpRequest
       .post("https://jsonplaceholder.typicode.com/posts")
       .send({ title: "post title" })
       .send({ body: "post body" })
       .then(function(res) {
         console.log(res.status);
         console.log(JSON.stringify(res.header, null, 4));
         console.log(JSON.stringify(res.body, null, 4));
       })
       .catch(function(err) {
         console.log(err.message)
         console.log(err.response)
       });
   }
 }

For more information on the http features of SuperAgent, please see their documentation.

Caching API of DuperAgent

The caching API of HttpRequest is super useful to locally cache results of your requests as fallback in case of network or server issues.

To set up the cache, you can use the config() method:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   Component.onCompleted: {
     HttpRequest.config({
       cache: true
     });
   }
 }

By default the cache is active and not limited in size. To deactivate the cache, set a maximum size or change the cache location, see the config() options. You can also change the caching behavior of individual HttpRequest items with the following methods:

  • var cacheSave(boolean)

    Overrides the cache save behavior for a single request. Setting it to true will enable caching, while false deactivates the cache.

  • var cacheLoad(´╗┐HttpCacheControl)

    This function is set to override the cache load behavior for a single request. It can have the following values:

    • HttpCacheControl.AlwaysNetwork
    • HttpCacheControl.PreferNetwork (default)
    • HttpCacheControl.PreferCache
    • HttpCacheControl.AlwaysCache

You can use them as shown in this example:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   Component.onCompleted: {
     HttpRequest
       .get("http://httpbin.org/get")
       .cacheSave(true) // cache the result of this request, regardless of global cache setting
       .cacheLoad(HttpCacheControl.PreferNetwork) // use network if possible, otherwise load from cache
       .then(function(res) {
         console.log(JSON.stringify(res.body))
       })
       .catch(function(err) {
         console.log(err.message)
       });
   }
 }

Note: The cache is only used if there is a working network connection and the request fails. HttpRequest will not use the cache if your device has no connection to the internet at all or is in flight mode.

Promise API of DuperAgent

The DuperAgent package also contains an implementation of the Promises/A+ specification and offers an API similar to the Promises API in ES2017. For more information, please see MDN.

The Promise type works independently of DuperAgent's http features and does not require the Http prefix. This is how you can create a Promise in QML to handle the result of an HttpRequest:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   Component.onCompleted: {

     var p = Promise.create(function(resolve, reject) {
       // handle asynchronous code here
       // e.g. with asynchronous HttpRequest
       HttpRequest
         .get("http://httpbin.org/get")
         .timeout(5000)
         .end(function (err, res) {
           if(res.ok)
             resolve(res.body)
           else
             reject(err.message)
         })
     });

     // execute promise and handle result
     p.then(function(value) {
        // success
       console.log("Value: "+JSON.stringify(value))
     }).catch(function(reason) {
       // failure
       console.log("Error: "+reason)
     });

   }
 }

Additional DuperAgent Components

Similar to HttpRequest, which matches the DuperAgent Request type, other DuperAgent components are also directly available in V-Play with the Http prefix:

Multiple HttpRequests with Promise, Caching and Activity Indicator

The following example combines multiple http requests with a promise, caching and an activity indicator:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {

   Component.onCompleted: {
     // remove activation delay to immediately show the indicator for requests
     // otherwise, requests that take less than the default 150 ms won't trigger the indicator
     HttpNetworkActivityIndicator.activationDelay = 0

     // configure caching
     HttpRequest.config({
       cache: { maxSize: 20000 } // max size of 200000 bytes
     })
   }

   NavigationStack {
     Page {
       id: myPage
       title: "HttpRequest Example"
       rightBarItem: ActivityIndicatorBarItem {
         animating: HttpNetworkActivityIndicator.enabled
         visible: animating
       }

       // HttpNetworkActivityIndicator is not supported with Promises
       // this example thus uses a custom activity indicator handling
       property bool promisePending: false

       // function to send all requests and handle the result
       function sendAllRequests() {
         // trigger first request
         var p1 = HttpRequest
           .get("https://jsonplaceholder.typicode.com/todos/1")
           .cacheSave(false) // do not save response of first request to cache
           .cacheLoad(HttpCacheControl.AlwaysNetwork) // always load from network
           .then(function(res){ return res.body; });

         // trigger second request
         var p2 = HttpRequest
           .get("https://jsonplaceholder.typicode.com/posts/1")
           .timeout(5000)
           .cacheLoad(HttpCacheControl.PreferCache) // use cache if possible, otherwise load from network
           .then(function(res){ return res.body; });

         // create promise to check success of both requests
         var allRequests = Promise.all([p1, p2])

         // handle promise result
         allRequests.then(function(values) {
           console.log("Both requests finished: "+JSON.stringify(values))
         }).catch(function (err) {
           console.log("Error: "+err)
         })
       }

       AppButton {
         text: "Send Get Requests"
         anchors.centerIn: parent
         onClicked: myPage.sendAllRequests()
       }
     }
   }
 }

Property Documentation

This property behaves similar to document.cookie as implemented in browsers.

It returns all cookies in the cookie jar as a semi-colon separated string. Note that it does not return cookies that are marked as HttpOnly.

Assigning a cookie to this property will add it to the cookie jar. If there is an existing cookie with the same identifying tuple, it will overwrite it. Note that it is not possible to overwrite cookies marked as HttpOnly. Attempts to overwrite these are silently ignored.

See also clearCookies.


Method Documentation

void clearCookies()

This function will clear all saved cookies including those marked as HttpOnly.

See also cookie.


void config(var options)

Allows to set global configuration options for the agent. This function should be called once before any requests are made. You can for example use the Component.onCompleted signal of your App window to call it on app start:

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   Component.onCompleted: {
     HttpRequest.config({
       cache: false
     });
   }
 }

The following configuration options are supported:

  • cache

    This option controls the cache behavior of the agent. The default is to create a QNetworkDiskCache with a sensible path for the platform. If you wish to disable this behavior, for example because you have your own cache, you can set this property to false. The property can be further customized by passing an object.

     import VPlayApps 1.0
     import QtQuick 2.0
    
     App {
       Component.onCompleted: {
         HttpRequest.config({
           cache: {
             maxSize: 20000,
             location: "/path/to/cache"
           }
         });
       }
     }

    The maxSize option specifies the maximum size of the cache. To specify a custom directory for caching files, use the location setting. The default location is <CacheLocation>/duperagent.

  • cookieJar

    This option controls the cookie jar of the agent. The default is to create an instance of a QNetworkCookieJar that additionally persists the cookies to disk. If you wish to disable this behavior, for example because you have your own cookie jar, you can set this property to false. This property can be further customized by passing an object.

     import VPlayApps 1.0
     import QtQuick 2.0
    
     App {
       Component.onCompleted: {
         HttpRequest.config({
           cookieJar: {
             location: "/path/to/cookies.txt"
           }
         });
       }
     }

    The location option specifies the full path to the file to use for the disk storage. The default is <AppDataLocation>/duperagent_cookies.txt.

  • proxy

    This option controls the proxy settings used by agent. By default Qt does not use a proxy, however you can use the system proxy by setting this value to "system".

     import VPlayApps 1.0
     import QtQuick 2.0
    
     App {
       Component.onCompleted: {
         HttpRequest.config({
           proxy: "system"
         });
       }
     }

var del(string url, var callback)

Creates an http DEL request for the given url. The callback parameter is optional.

Similar to the HttpRequest::get() function, the returned request object allows to specify additional request settings or send the request.

See also get, head, patch, post, and put.


var get(string url, var data, var callback)

Creates an http GET request for the given url. The data and callback parameters are optional. In case a callback function is specified, the data parameter may be skipped.

The function returns a request object, which in turn allows to specify additional request settings or send the request. For example, you can use timeout to specify the maximum request timeout. Then call the end function to send the request and handle the result.

 import VPlayApps 1.0
 import QtQuick 2.0

 App {
   Component.onCompleted: {
     HttpRequest
       .get("http://httpbin.org/get")
       .timeout(5000)
       .end(function(err, res) {
         if(res.ok) {
           console.log(res.status);
           console.log(JSON.stringify(res.header, null, 4));
           console.log(JSON.stringify(res.body, null, 4));
         }
         else {
           console.log(err.message)
           console.log(err.response)
         }
       });
   }
 }

See also head, del, patch, post, and put.


var head(string url, var data, var callback)

Creates an http HEAD request for the given url. The data and callback parameters are optional. In case a callback function is specified, the data parameter may be skipped.

Similar to the HttpRequest::get() function, the returned request object allows to specify additional request settings or send the request.

See also get, del, patch, post, and put.


var patch(string url, var data, var callback)

Creates an http PATCH request for the given url. The data and callback parameters are optional. In case a callback function is specified, the data parameter may be skipped.

Similar to the HttpRequest::get() function, the returned request object allows to specify additional request settings or send the request.

See also get, head, del, post, and put.


var post(string url, var data, var callback)

Creates an http POST request for the given url. The data and callback parameters are optional. In case a callback function is specified, the data parameter may be skipped.

Similar to the HttpRequest::get() function, the returned request object allows to specify additional request settings or send the request.

See also get, head, del, patch, and put.


var put(string url, var data, var callback)

Creates an http PUT request for the given url. The data and callback parameters are optional. In case a callback function is specified, the data parameter may be skipped.

Similar to the HttpRequest::get() function, the returned request object allows to specify additional request settings or send the request.

See also get, head, del, patch, and post.


Voted #1 for:

  • Easiest to learn
  • Most time saving
  • Best support

Develop Cross-Platform Apps and Games 50% Faster!

  • Voted the best supported, most time-saving and easiest to learn cross-platform development tool
  • Based on the Qt framework, with native performance and appearance on all platforms including iOS and Android
  • Offers a variety of plugins to monetize, analyze and engage users
FREE!
create apps
create games
cross platform
native performance
3rd party services
game network
multiplayer
level editor
easiest to learn
biggest time saving
best support