Search code examples
c++qurl

How can I include a percent sign in QUrl


I'm new in c++ from this afternoon and I am having a hard time.

I have the below line:

const QUrl command("http://192.168.11.11/subdomain/letters?t=somekeyword&p=%01")

But when the QUrl "command" is sent used in QNetworkAccessManager, it is actually being sent adding 25 after the % sign. Now I understand that QUrl is in TolerantMode, and is adding it thinking it's a user input error.

Unwanted result:

http://192.168.11.11/subdomain/letters?t=somekeyword&p=%2501

How would I prevent my url to be modified?

I tried to double my percent sign and inserting a backslash as well.

Any help is appreciated. Thanks.


Solution

  • This turned out to be a tricky problem. Here is the solution I came up with:

    Code

    QByteArray rawQuery("t=somekeyword&p=%01");
    QUrl command("http://192.168.11.11/subdomain/letters");
    command.setEncodedQuery(rawQuery);
    std::cout << command.toEncoded().data();
    

    Result

    http://192.168.11.11/subdomain/letters?t=somekeyword&p=%01

    Notes

    The solution relies on some behavior described in setEncodedQuery, which states

    Sets the query string of the URL to query. The string is inserted as-is, and no further encoding is performed when calling toEncoded().

    This function is useful if you need to pass a query string that does not fit into the key-value pattern, or that uses a different scheme for encoding special characters than what is suggested by QUrl.

    Passing a value of QByteArray() to query (a null QByteArray) unsets the query completely. However, passing a value of QByteArray("") will set the query to an empty value, as if the original URL had a lone "?".

    References