c++qtqtcoreqtnetworkqdesktopservices

Qt QDesktopServices::openUrl - launch browser with post values


I'm trying to write a simple application that will launch a browser and send it to a URL based on a user's input.

QDesktopServices::openUrl(QUrl(url));

However, I'd like to pass variables along with whatever URL they submit using POST. For GET, all I'd need to do is simply embed the values into the URL string, but how would I go about adding POST variables?.

Thanks.


Solution

  • From the official documentation:

    bool QDesktopServices::openUrl(const QUrl & url) [static]

    Opens the given url in the appropriate Web browser for the user's desktop environment, and returns true if successful; otherwise returns false.

    If the URL is a reference to a local file (i.e., the URL scheme is "file") then it will be opened with a suitable application instead of a Web browser.

    The short answer is that it was not meant to be a network managet. For that purpose, one could already use the QNetworkAccessManager. It was just a convenient way to add support for opening up an URL as that would require quite a bit of work otherwise. There were no further plans to it to replicate QtNetwork more closely.

    Thereby, I would suggest to use something like this to achieve working with post methods given your url:

    QUrlQuery urlQuery;
    urlQuery.addQueryItem("param1", "value1");
    urlQuery.addQueryItem("param2", "value2");
    QUrl url = QUrl("http://foo.com");
    QNetworkRequest networkRequest(url);
    networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    networkManager->post(networkRequest, urlQuery.toString(QUrl::FullyEncoded).toUtf8());