QNetworkReply Class Reference

The QNetworkReply class contains the data and headers for a request sent with QNetworkAccessManager

  1. #include <QNetworkReply>

Inherits: QIODevice.

Note: All functions in this class are reentrant.

This class was introduced in Qt 4.4.

Detailed Description

The QNetworkReply class contains the data and headers for a request sent with QNetworkAccessManager

The QNetworkReply class contains the data and meta data related to a request posted with QNetworkAccessManager. Like QNetworkRequest, it contains a URL and headers (both in parsed and raw form), some information about the reply's state and the contents of the reply itself.

QNetworkReply is a sequential-access QIODevice, which means that once data is read from the object, it no longer kept by the device. It is therefore the application's responsibility to keep this data if it needs to. Whenever more data is received from the network and processed, the readyRead() signal is emitted.

The downloadProgress() signal is also emitted when data is received, but the number of bytes contained in it may not represent the actual bytes received, if any transformation is done to the contents (for example, decompressing and removing the protocol overhead).

Even though QNetworkReply is a QIODevice connected to the contents of the reply, it also emits the uploadProgress() signal, which indicates the progress of the upload for operations that have such content.

Note: Do not delete the object in the slot connected to the error() or finished() signal. Use deleteLater().

See also QNetworkRequest and QNetworkAccessManager.

Public Types

Toggle detailsenum QNetworkReply::

NetworkErrorNetworkError { NoError , ConnectionRefusedError , RemoteHostClosedError , HostNotFoundError , TimeoutError , OperationCanceledError , SslHandshakeFailedError , TemporaryNetworkFailureError , UnknownNetworkError , ProxyConnectionRefusedError , ProxyConnectionClosedError , ProxyNotFoundError , ProxyTimeoutError , ProxyAuthenticationRequiredError , UnknownProxyError , ContentAccessDenied , ContentOperationNotPermittedError , ContentNotFoundError , AuthenticationRequiredError , ContentReSendError , UnknownContentError , ProtocolUnknownError , ProtocolInvalidOperationError , ProtocolFailure 399 ...} { NoError , ConnectionRefusedError , RemoteHostClosedError , HostNotFoundError , TimeoutError , OperationCanceledError , SslHandshakeFailedError , TemporaryNetworkFailureError , UnknownNetworkError , ProxyConnectionRefusedError , ProxyConnectionClosedError , ProxyNotFoundError , ProxyTimeoutError , ProxyAuthenticationRequiredError , UnknownProxyError , ContentAccessDenied , ContentOperationNotPermittedError , ContentNotFoundError , AuthenticationRequiredError , ContentReSendError , UnknownContentError , ProtocolUnknownError , ProtocolInvalidOperationError , ProtocolFailure 399 }

Indicates all possible error conditions found during the processing of the request.

ConstantValueDescription
QNetworkReply::NoError 0 no error condition. Note: When the HTTP protocol returns a redirect no error will be reported. You can check if there is a redirect with the QNetworkRequest::RedirectionTargetAttribute attribute.
QNetworkReply::ConnectionRefusedError 1 the remote server refused the connection (the server is not accepting requests)
QNetworkReply::RemoteHostClosedError 2 the remote server closed the connection prematurely, before the entire reply was received and processed
QNetworkReply::HostNotFoundError 3 the remote host name was not found (invalid hostname)
QNetworkReply::TimeoutError 4 the connection to the remote server timed out
QNetworkReply::OperationCanceledError 5 the operation was canceled via calls to abort() or close() before it was finished.
QNetworkReply::SslHandshakeFailedError 6 the SSL/TLS handshake failed and the encrypted channel could not be established. The sslErrors() signal should have been emitted.
QNetworkReply::TemporaryNetworkFailureError 7 the connection was broken due to disconnection from the network, however the system has initiated roaming to another access point. The request should be resubmitted and will be processed as soon as the connection is re-established.
QNetworkReply::ProxyConnectionRefusedError 101 the connection to the proxy server was refused (the proxy server is not accepting requests)
QNetworkReply::ProxyConnectionClosedError 102 the proxy server closed the connection prematurely, before the entire reply was received and processed
QNetworkReply::ProxyNotFoundError 103 the proxy host name was not found (invalid proxy hostname)
QNetworkReply::ProxyTimeoutError 104 the connection to the proxy timed out or the proxy did not reply in time to the request sent
QNetworkReply::ProxyAuthenticationRequiredError 105 the proxy requires authentication in order to honour the request but did not accept any credentials offered (if any)
QNetworkReply::ContentAccessDenied 201 the access to the remote content was denied (similar to HTTP error 401)
QNetworkReply::ContentOperationNotPermittedError 202 the operation requested on the remote content is not permitted
QNetworkReply::ContentNotFoundError 203 the remote content was not found at the server (similar to HTTP error 404)
QNetworkReply::AuthenticationRequiredError 204 the remote server requires authentication to serve the content but the credentials provided were not accepted (if any)
QNetworkReply::ContentReSendError 205 the request needed to be sent again, but this failed for example because the upload data could not be read a second time.
QNetworkReply::ProtocolUnknownError 301 the Network Access API cannot honor the request because the protocol is not known
QNetworkReply::ProtocolInvalidOperationError 302 the requested operation is invalid for this protocol
QNetworkReply::UnknownNetworkError 99 an unknown network-related error was detected
QNetworkReply::UnknownProxyError 199 an unknown proxy-related error was detected
QNetworkReply::UnknownContentError 299 an unknown error related to the remote content was detected
QNetworkReply::ProtocolFailure 399 a breakdown in protocol was detected (parsing error, invalid or unexpected responses, etc.)

See also error().

Look up this member in the source code.

    Types

    Toggle detailstypedef QNetworkReply RawHeaderPairRawHeaderPair

    RawHeaderPair is a QPair<QByteArray, QByteArray> where the first QByteArray is the header name and the second is the header.

    Look up this member in the source code.

      Public Functions

      Toggle details QNetworkReply

      QNetworkReplyQNetworkReply ( QObject *parent=0 ) ( QObject *parent=0 )[protected]

      Creates a QNetworkReply object with parent parent.

      You cannot directly instantiate QNetworkReply objects. Use QNetworkAccessManager functions to do that.

      Look up this member in the source code.

      Toggle details QNetworkReply

      ~QNetworkReply~QNetworkReply () ()

      Disposes of this reply and frees any resources associated with it. If any network connections are still open, they will be closed.

      See also abort() and close().

      Look up this member in the source code.

      Toggle details void QNetworkReply

      abortabort () () [pure virtual]

      Aborts the operation immediately and close down any network connections still open. Uploads still in progress are also aborted.

      See also close().

      Look up this member in the source code.

      Toggle details QVariant QNetworkReply

      attributeattribute ( QNetworkRequest::Attribute code ...) ( QNetworkRequest::Attribute code )const

      Returns the attribute associated with the code code. If the attribute has not been set, it returns an invalid QVariant (type QVariant::Null).

      You can expect the default values listed in QNetworkRequest::Attribute to be applied to the values returned by this function.

      See also setAttribute() and QNetworkRequest::Attribute.

      Look up this member in the source code.

      Toggle details void QNetworkReply

      closeclose () () [virtual]

      Reimplemented from QIODevice::close().

      Closes this device for reading. Unread data is discarded, but the network resources are not discarded until they are finished. In particular, if any upload is in progress, it will continue until it is done.

      The finished() signal is emitted when all operations are over and the network resources are freed.

      See also abort() and finished().

      Look up this member in the source code.

      Toggle details NetworkError QNetworkReply

      errorerror () ()const

      Returns the error that was found during the processing of this request. If no error was found, returns NoError.

      See also setError().

      Look up this member in the source code.

      Toggle details bool QNetworkReply

      hasRawHeaderhasRawHeader ( const QByteArray &headerName ) ( const QByteArray &headerName )const

      Returns true if the raw header of name headerName was sent by the remote server

      See also rawHeader().

      Look up this member in the source code.

      Toggle details QVariant QNetworkReply

      headerheader ( QNetworkRequest::KnownHeaders header ...) ( QNetworkRequest::KnownHeaders header )const

      Returns the value of the known header header, if that header was sent by the remote server. If the header was not sent, returns an invalid QVariant.

      See also rawHeader(), setHeader(), and QNetworkRequest::header().

      Look up this member in the source code.

      Toggle details void QNetworkReply

      ignoreSslErrorsignoreSslErrors ( const QList <QSslError > &errors ...) ( const QList <QSslError > &errors )

      This is an overloaded function.

      If this function is called, the SSL errors given in errors will be ignored.

      Note that you can set the expected certificate in the SSL error: If, for instance, you want to issue a request to a server that uses a self-signed certificate, consider the following snippet:

      1.                     QList<QSslCertificate> cert = QSslCertificate::fromPath(QLatin1String("server-certificate.pem"));
      2. QSslError error(QSslError::SelfSignedCertificate, cert.at(0));
      3. QList<QSslError> expectedSslErrors;
      4. expectedSslErrors.append(error);
      5.  
      6. QNetworkReply *reply = manager.get(QNetworkRequest(QUrl("https://server.tld/index.html")));
      7. reply->ignoreSslErrors(expectedSslErrors);
      8. // here connect signals etc.

      Multiple calls to this function will replace the list of errors that were passed in previous calls. You can clear the list of errors you want to ignore by calling this function with an empty list.

      See also sslConfiguration(), sslErrors(), and QSslSocket::ignoreSslErrors().

      Look up this member in the source code.

      Toggle details bool QNetworkReply

      isFinishedisFinished () ()const

      Returns true when the reply has finished or was aborted.

      See also isRunning().

      Look up this member in the source code.

      Toggle details bool QNetworkReply

      isRunningisRunning () ()const

      Returns true when the request is still processing and the reply has not finished or was aborted yet.

      See also isFinished().

      Look up this member in the source code.

      Toggle details QNetworkAccessManager * QNetworkReply

      managermanager () ()const

      Returns the QNetworkAccessManager that was used to create this QNetworkReply object. Initially, it is also the parent object.

      Look up this member in the source code.

      Toggle details QNetworkAccessManager::Operation QNetworkReply

      operationoperation () ()const

      Returns the operation that was posted for this reply.

      See also setOperation().

      Look up this member in the source code.

      Toggle details QByteArray QNetworkReply

      rawHeaderrawHeader ( const QByteArray &headerName ( const QByteArray &headerName )const

      Returns the raw contents of the header headerName as sent by the remote server. If there is no such header, returns an empty byte array, which may be indistinguishable from an empty header. Use hasRawHeader() to verify if the server sent such header field.

      See also setRawHeader(), hasRawHeader(), and header().

      Look up this member in the source code.

      Toggle details QList <QByteArray > QNetworkReply

      rawHeaderListrawHeaderList () ()const

      Returns a list of headers fields that were sent by the remote server, in the order that they were sent. Duplicate headers are merged together and take place of the latter duplicate.

      Look up this member in the source code.

      Toggle details const QList <RawHeaderPair > & QNetworkReply

      rawHeaderPairsrawHeaderPairs () ()const

      Returns a list of raw header pairs.

      Look up this member in the source code.

      Toggle details qint64 QNetworkReply

      readBufferSizereadBufferSize () ()const

      Returns the size of the read buffer, in bytes.

      See also setReadBufferSize().

      Look up this member in the source code.

      Toggle details QNetworkRequest QNetworkReply

      requestrequest () ()const

      Returns the request that was posted for this reply. In special, note that the URL for the request may be different than that of the reply.

      See also QNetworkRequest::url(), url(), and setRequest().

      Look up this member in the source code.

      Toggle details void QNetworkReply

      setAttributesetAttribute ( QNetworkRequest::Attribute code , const QVariant &value ...) ( QNetworkRequest::Attribute code , const QVariant &value )[protected]

      Sets the attribute code to have value value. If code was previously set, it will be overridden. If value is an invalid QVariant, the attribute will be unset.

      See also attribute() and QNetworkRequest::setAttribute().

      Look up this member in the source code.

      Toggle details void QNetworkReply

      setErrorsetError ( NetworkError errorCode , const QString &errorString ...) ( NetworkError errorCode , const QString &errorString )[protected]

      Sets the error condition to be errorCode. The human-readable message is set with errorString.

      Calling setError() does not emit the error(QNetworkReply::NetworkError) signal.

      See also error() and errorString().

      Look up this member in the source code.

      Toggle details void QNetworkReply

      setHeadersetHeader ( QNetworkRequest::KnownHeaders header , const QVariant &value ...) ( QNetworkRequest::KnownHeaders header , const QVariant &value )[protected]

      Sets the known header header to be of value value. The corresponding raw form of the header will be set as well.

      See also header(), setRawHeader(), and QNetworkRequest::setHeader().

      Look up this member in the source code.

      Toggle details void QNetworkReply

      setOperationsetOperation ( QNetworkAccessManager::Operation operation ...) ( QNetworkAccessManager::Operation operation )[protected]

      Sets the associated operation for this object to be operation. This value will be returned by operation().

      Note: the operation should be set when this object is created and not changed again.

      See also operation() and setRequest().

      Look up this member in the source code.

      Toggle details void QNetworkReply

      setRawHeadersetRawHeader ( const QByteArray &headerName , const QByteArray &value ...) ( const QByteArray &headerName , const QByteArray &value )[protected]

      Sets the raw header headerName to be of value value. If headerName was previously set, it is overridden. Multiple HTTP headers of the same name are functionally equivalent to one single header with the values concatenated, separated by commas.

      If headerName matches a known header, the value value will be parsed and the corresponding parsed form will also be set.

      See also rawHeader(), header(), setHeader(), and QNetworkRequest::setRawHeader().

      Look up this member in the source code.

      Toggle details void QNetworkReply

      setReadBufferSizesetReadBufferSize ( qint64 size ) ( qint64 size ) [virtual]

      Sets the size of the read buffer to be size bytes. The read buffer is the buffer that holds data that is being downloaded off the network, before it is read with QIODevice::read(). Setting the buffer size to 0 will make the buffer unlimited in size.

      QNetworkReply will try to stop reading from the network once this buffer is full (i.e., bytesAvailable() returns size or more), thus causing the download to throttle down as well. If the buffer is not limited in size, QNetworkReply will try to download as fast as possible from the network.

      Unlike QAbstractSocket::setReadBufferSize(), QNetworkReply cannot guarantee precision in the read buffer size. That is, bytesAvailable() can return more than size.

      See also readBufferSize().

      Look up this member in the source code.

      Toggle details void QNetworkReply

      setRequestsetRequest ( const QNetworkRequest &request ) ( const QNetworkRequest &request )[protected]

      Sets the associated request for this object to be request. This value will be returned by request().

      Note: the request should be set when this object is created and not changed again.

      See also request() and setOperation().

      Look up this member in the source code.

      Toggle details void QNetworkReply

      setSslConfigurationsetSslConfiguration ( const QSslConfiguration &config ...) ( const QSslConfiguration &config )

      Sets the SSL configuration for the network connection associated with this request, if possible, to be that of config.

      See also sslConfiguration().

      Look up this member in the source code.

      Toggle details void QNetworkReply

      setUrlsetUrl ( const QUrl &url ) ( const QUrl &url )[protected]

      Sets the URL being processed to be url. Normally, the URL matches that of the request that was posted, but for a variety of reasons it can be different (for example, a file path being made absolute or canonical).

      See also url(), request(), and QNetworkRequest::url().

      Look up this member in the source code.

      Toggle details QSslConfiguration QNetworkReply

      sslConfigurationsslConfiguration () ()const

      Returns the SSL configuration and state associated with this reply, if SSL was used. It will contain the remote server's certificate, its certificate chain leading to the Certificate Authority as well as the encryption ciphers in use.

      The peer's certificate and its certificate chain will be known by the time sslErrors() is emitted, if it's emitted.

      See also setSslConfiguration().

      Look up this member in the source code.

      Toggle details QUrl QNetworkReply

      urlurl () ()const

      Returns the URL of the content downloaded or uploaded. Note that the URL may be different from that of the original request.

      See also request(), setUrl(), and QNetworkRequest::url().

      Look up this member in the source code.

        Signals

        Toggle details void QNetworkReply

        downloadProgressdownloadProgress ( qint64 bytesReceived , qint64 bytesTotal ...) ( qint64 bytesReceived , qint64 bytesTotal ) [signal]

        This signal is emitted to indicate the progress of the download part of this network request, if there's any. If there's no download associated with this request, this signal will be emitted once with 0 as the value of both bytesReceived and bytesTotal.

        The bytesReceived parameter indicates the number of bytes received, while bytesTotal indicates the total number of bytes expected to be downloaded. If the number of bytes to be downloaded is not known, bytesTotal will be -1.

        The download is finished when bytesReceived is equal to bytesTotal. At that time, bytesTotal will not be -1.

        Note that the values of both bytesReceived and bytesTotal may be different from size(), the total number of bytes obtained through read() or readAll(), or the value of the header(ContentLengthHeader). The reason for that is that there may be protocol overhead or the data may be compressed during the download.

        See also uploadProgress() and bytesAvailable().

        Look up this member in the source code.

        Toggle details void QNetworkReply

        errorerror ( QNetworkReply::NetworkError code ) ( QNetworkReply::NetworkError code ) [signal]

        This signal is emitted when the reply detects an error in processing. The finished() signal will probably follow, indicating that the connection is over.

        The code parameter contains the code of the error that was detected. Call errorString() to obtain a textual representation of the error condition.

        Note: Do not delete the object in the slot connected to this signal. Use deleteLater().

        See also error() and errorString().

        Look up this member in the source code.

        Toggle details void QNetworkReply

        finishedfinished () () [signal]

        This signal is emitted when the reply has finished processing. After this signal is emitted, there will be no more updates to the reply's data or metadata.

        Unless close() has been called, the reply will be still be opened for reading, so the data can be retrieved by calls to read() or readAll(). In particular, if no calls to read() were made as a result of readyRead(), a call to readAll() will retrieve the full contents in a QByteArray.

        This signal is emitted in tandem with QNetworkAccessManager::finished() where that signal's reply parameter is this object.

        Note: Do not delete the object in the slot connected to this signal. Use deleteLater().

        You can also use isFinished() to check if a QNetworkReply has finished even before you receive the finished() signal.

        See also QNetworkAccessManager::finished() and isFinished().

        Look up this member in the source code.

        Toggle details void QNetworkReply

        metaDataChangedmetaDataChanged () () [signal]

        This signal is emitted whenever the metadata in this reply changes. metadata is any information that is not the content (data) itself, including the network headers. In the majority of cases, the metadata will be known fully by the time the first byte of data is received. However, it is possible to receive updates of headers or other metadata during the processing of the data.

        See also header(), rawHeaderList(), rawHeader(), and hasRawHeader().

        Look up this member in the source code.

        Toggle details void QNetworkReply

        sslErrorssslErrors ( const QList <QSslError > &errors ) ( const QList <QSslError > &errors ) [signal]

        This signal is emitted if the SSL/TLS session encountered errors during the set up, including certificate verification errors. The errors parameter contains the list of errors.

        To indicate that the errors are not fatal and that the connection should proceed, the ignoreSslErrors() function should be called from the slot connected to this signal. If it is not called, the SSL session will be torn down before any data is exchanged (including the URL).

        This signal can be used to display an error message to the user indicating that security may be compromised and display the SSL settings (see sslConfiguration() to obtain it). If the user decides to proceed after analyzing the remote certificate, the slot should call ignoreSslErrors().

        See also QSslSocket::sslErrors(), QNetworkAccessManager::sslErrors(), sslConfiguration(), and ignoreSslErrors().

        Look up this member in the source code.

        Toggle details void QNetworkReply

        uploadProgressuploadProgress ( qint64 bytesSent , qint64 bytesTotal ...) ( qint64 bytesSent , qint64 bytesTotal ) [signal]

        This signal is emitted to indicate the progress of the upload part of this network request, if there's any. If there's no upload associated with this request, this signal will not be emitted.

        The bytesSent parameter indicates the number of bytes uploaded, while bytesTotal indicates the total number of bytes to be uploaded. If the number of bytes to be uploaded could not be determined, bytesTotal will be -1.

        The upload is finished when bytesSent is equal to bytesTotal. At that time, bytesTotal will not be -1.

        See also downloadProgress().

        Look up this member in the source code.

          Public Slots

          Toggle details void QNetworkReply

          ignoreSslErrorsignoreSslErrors () () [virtual] [slot]

          If this function is called, SSL errors related to network connection will be ignored, including certificate validation errors.

          Note that calling this function without restraint may pose a security risk for your application. Use it with care.

          This function can be called from the slot connected to the sslErrors() signal, which indicates which errors were found.

          See also sslConfiguration(), sslErrors(), and QSslSocket::ignoreSslErrors().

          Look up this member in the source code.

            Notes provided by the Qt Community
            Cool Hack
            • 4

            Votes: 3

            Coverage: Qt library 4.7, 4.8, 5.0

            Picture of minimoog77 minimoog77

            Lab Rat
            2 notes

            Passing data to QNetworkReply

            You can add custom data to QNetworkReply with using dynamic properties, then in the connected finished slot you can query the data.

            1. QNetworkReply *reply = networkAccessManager->get(QNetworkRequest(QUrl("http://someurl.com"));
            2. reply->setProperty("mycustomdata", QVariant("example of data");
            3. connect(reply, SIGNAL(finished()), this, SLOT(replyFinished()));

            Then in replyFinished slot you can query custom data:

            1. QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
            2.  
            3. if (reply) {
            4.     if (reply->error() == QNetworkReply::NoError) {
            5.         QString myCustomData = reply->property("mycustomdata").toString();
            6.     }
            7.  
            8.     reply->deleteLater();
            9. }

            [Revisions]