c++qtcookiesqnetworkaccessmanager

Best way to share cookies within Qt application


I can use QNetworkCookieJar to retrieve, store and resend cookies of a QNetworkManager. Multiple QNetworkAccessManager instances can share a single QNetworkCookieJar.

So far I have used multiple QNetworkAccessManager instances, one per class (where I need to read):

  1. So I could have a singleton QNetworkCookieJar shared across 1..n QNetworkAccessManager instances
  2. Or is it better to have only a singleton QNetworkAccessManager with one Jar shared across all QNetworkRequests. Is QNetworkAccessManager as single object the way to go? Documentation says there should only be one instance. So would I better use a singleton QNetworkAccessManager?

What would be the most appropriate way to go?

------ Edit -------

kkoehne's answer is correct from what I can tell. Also it is what documentation says. However, when trying this approach I have noticed 2 issues:

  1. While we have now one QNetworkAccessManager per web service, changing to one single instance means I need to always distinguish what kind of content I just receive in the "finished" slot (the one called from QNetworkAccessManager::finished). That's feasible, but inconvenient.
  2. We run our readers in different threads - I forgot to mention this in the question unfortunately. That makes it almost impossible to use a single instance of QNetworkAccessManager, as the member functions are reentrant, but not thread safe. ( QNetworkAccessManager from ThreadPool )

Related: QNetworkAccessManager get/post from different thread possible?


Solution

  • I assume you're referring to QNetworkAccessManager, not QNetworkManager.

    You should prefer having a single QNetworkAccessManager in your application. This not only gets rid of any need to synchronize QNetworkCookieJar's, but also makes sure that the network is best utilized, and that cached content etc is shared.

    As you noticed yourself, this is also hinted in the QtNetworkAccessManager documentation:

    One QNetworkAccessManager should be enough for the whole Qt application.