POST using Qt5



  • I'm stumbling my way through communicating with a web service and failing badly.. I'm trying to mimic a form that POSTs a chunk of json data to the server in a "json" field. There are similar questions here on Qt Project and elsewhere, but most are using the 4.x APIs which don't translate directly. Help!

    Here's what I'm trying (simplified a little):

    @
    QUrl url("http://.....");
    QUrlQuery query;
    query.addQueryItem("json", <json text as QString>);
    url.setQuery(query);
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    QNetworkAccessManager net(this);
    net.get(request);
    @

    It seems strange to be using "get" to POST data... also the docs suggest that addQueryItem() does not do what a browser would do with a form (converting spaces to pluses) but doesn't give any advice on whether that is important or not.

    Any help would be most appreciated!


  • Moderators

    [quote author="rosetter" date="1389792547"]
    It seems strange to be using "get" to POST data...
    [/quote]
    Indeed, where to you got this example from?!

    @
    QByteArray postData;
    postData.append("json=<json-data>&");
    postData.append("other=<other-data>");

    QNetworkRequest request( QUrl("...") );
            request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    
    QNetworkAccessManager* net = ...;
    QNetworkReply* reply = net->post(request, postData);
    connect(reply, SIGNAL(...), ..., SLOT(...);
    

    @
    Make sure you use a QNetworkAccessManager by pointer value, or as class member. Just not in a stack variable with function scope...



  • Hi, thanks for the quick reply! Unfortunately I'm still super-confused..

    • do I need to do some kind of encoding of postData? (% encoding? space -> '+'?)
    • what about QUrlQuery? is it not intended to be helpful in POSTs?
    • is there some way I can see what is actually being sent over the network?

  • Moderators

    [quote author="rosetter" date="1389970769"]

    • do I need to do some kind of encoding of postData? (% encoding? space -> '+'?)
    • what about QUrlQuery? is it not intended to be helpful in POSTs?
      [/quote]
      yes you would need to do the encoding yourself. But still you can use QUrlQuery::query().

    [quote author="rosetter" date="1389970769"]

    • is there some way I can see what is actually being sent over the network?
      [/quote]
      Not on Qt level. You can use a proxy/sniffer application like "wireshark":http://www.wireshark.org.

Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.