Sending an HTTP request using QNetworkAccessManager

前端 未结 3 1805
闹比i
闹比i 2020-12-22 12:27

I\'ve got a problem trying to send a request using QNetworkAccessManager from a QObject derived class.

Firstly in my constructor I do the following:

         


        
相关标签:
3条回答
  • 2020-12-22 12:55

    A few points:

    1) The thread your QNetworkRequest belongs to must be running event loop (only this way you can receive signals).

    2) If you "wait around" with something like sleep after mAccessManager.post it is not going to work. You have to let event loop iterate to process signals, etc. You can run event loop yourself after post.

    ADD:

    I did it synchronously like this

    QNetworkRequest request;
    
    request.setHeader(
                QNetworkRequest::ContentTypeHeader,
                QVariant( QString("text/xml") )
                );
    request.setHeader(
                QNetworkRequest::ContentLengthHeader,
                QVariant( qulonglong(mesPOST.size()) )
                );
    request.setHeader(...);
    //etc....
    
    request.setAttribute(
                QNetworkRequest::CacheLoadControlAttribute,
                QVariant( int(QNetworkRequest::AlwaysNetwork) )
                );
    request.setUrl( QUrl( "http://bla.bla", QUrl::StrictMode ) );
    
    QNetworkReply* pReply = m_NetMgr->post( request, mesPOST );
    QEventLoop eLoop;
    
    QObject::connect( pReply, SIGNAL(finished()), &eLoop, SLOT(quit()) );
    eLoop.exec( QEventLoop::ExcludeUserInputEvents );
    
    0 讨论(0)
  • 2020-12-22 13:12

    I think this is because QNetworkAccessManager is asynchronous and need the time to send the request. But require, url, query, ... is destroyed when out of scope.
    -> we need in scope when QNetworkAccessManager do send request (use QEventLoop().exec(); ) or let require, url, query, ... is persistent (declare it with static). See: Qt: QNetworkAccessManager dont send request

    0 讨论(0)
  • 2020-12-22 13:20

    Ok so it turns out the problem is caused byt the fact that Qt does not include SSL support by default.

    http://doc.qt.nokia.com/4.7/ssl.html

    0 讨论(0)
提交回复
热议问题