Friday, September 8, 2017

Using a custom QNetworkAccessManager in QML

The QML Image component has the capability to specify the source of the image is as a URL (using the "source" property) and QML automatically retrieving such image file from a remote location. To do so, QML uses a QNetworkAccessManager (QNAM for short) in the background, which has a lot of default values. But what if you need to set some custom values for the QNAM?
I'll use this post in Qt forum for a real example. The QML application was showing this error:
QML Image: Error transferring http://whatever-server-name/Upload/Image/d574dc8c926cef3cab4c58f.jpeg - server replied: Not Acceptable
which was indeed an HTTP error 406. From examining the server logs, it turned out that the User Agent sent by QML was not accepted as valid by the server (as a security measure).
The solution involved changing the user agent header to a suitable value, but how to achieve that?
Let's introduce the QQmlNetworkAccessManagerFactory class, which allows to to provide the QML engine with custom QNetworkAccessManager instances tweaked to particular needs. There's a complete example about the whole concept here.

No comments:

Post a Comment