source: trunk/src/network/access/qnetworkreply.cpp@ 890

Last change on this file since 890 was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

File size: 24.3 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtNetwork module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "qnetworkreply.h"
43#include "qnetworkreply_p.h"
44#include <QtNetwork/qsslconfiguration.h>
45
46QT_BEGIN_NAMESPACE
47
48QNetworkReplyPrivate::QNetworkReplyPrivate()
49 : readBufferMaxSize(0),
50 operation(QNetworkAccessManager::UnknownOperation),
51 errorCode(QNetworkReply::NoError)
52{
53 // set the default attribute values
54 attributes.insert(QNetworkRequest::ConnectionEncryptedAttribute, false);
55}
56
57
58/*!
59 \class QNetworkReply
60 \since 4.4
61 \brief The QNetworkReply class contains the data and headers for a request
62 sent with QNetworkAccessManager
63
64 \reentrant
65 \ingroup network
66 \inmodule QtNetwork
67
68 The QNetworkReply class contains the data and meta data related to
69 a request posted with QNetworkAccessManager. Like QNetworkRequest,
70 it contains a URL and headers (both in parsed and raw form), some
71 information about the reply's state and the contents of the reply
72 itself.
73
74 QNetworkReply is a sequential-access QIODevice, which means that
75 once data is read from the object, it no longer kept by the
76 device. It is therefore the application's responsibility to keep
77 this data if it needs to. Whenever more data is received from the
78 network and processed, the readyRead() signal is emitted.
79
80 The downloadProgress() signal is also emitted when data is
81 received, but the number of bytes contained in it may not
82 represent the actual bytes received, if any transformation is done
83 to the contents (for example, decompressing and removing the
84 protocol overhead).
85
86 Even though QNetworkReply is a QIODevice connected to the contents
87 of the reply, it also emits the uploadProgress() signal, which
88 indicates the progress of the upload for operations that have such
89 content.
90
91 \note Do not delete the object in the slot connected to the
92 error() or finished() signal. Use deleteLater().
93
94 \sa QNetworkRequest, QNetworkAccessManager
95*/
96
97/*!
98 \enum QNetworkReply::NetworkError
99
100 Indicates all possible error conditions found during the
101 processing of the request.
102
103 \value NoError no error condition.
104 \note When the HTTP protocol returns a redirect no error will be
105 reported. You can check if there is a redirect with the
106 QNetworkRequest::RedirectionTargetAttribute attribute.
107
108 \value ConnectionRefusedError the remote server refused the
109 connection (the server is not accepting requests)
110
111 \value RemoteHostClosedError the remote server closed the
112 connection prematurely, before the entire reply was received and
113 processed
114
115 \value HostNotFoundError the remote host name was not found
116 (invalid hostname)
117
118 \value TimeoutError the connection to the remote server
119 timed out
120
121 \value OperationCanceledError the operation was canceled via calls
122 to abort() or close() before it was finished.
123
124 \value SslHandshakeFailedError the SSL/TLS handshake failed and the
125 encrypted channel could not be established. The sslErrors() signal
126 should have been emitted.
127
128 \value TemporaryNetworkFailureError the connection was broken due
129 to disconnection from the network, however the system has initiated
130 roaming to another access point. The request should be resubmitted
131 and will be processed as soon as the connection is re-established.
132
133 \value ProxyConnectionRefusedError the connection to the proxy
134 server was refused (the proxy server is not accepting requests)
135
136 \value ProxyConnectionClosedError the proxy server closed the
137 connection prematurely, before the entire reply was received and
138 processed
139
140 \value ProxyNotFoundError the proxy host name was not
141 found (invalid proxy hostname)
142
143 \value ProxyTimeoutError the connection to the proxy
144 timed out or the proxy did not reply in time to the request sent
145
146 \value ProxyAuthenticationRequiredError the proxy requires
147 authentication in order to honour the request but did not accept
148 any credentials offered (if any)
149
150 \value ContentAccessDenied the access to the remote
151 content was denied (similar to HTTP error 401)
152
153 \value ContentOperationNotPermittedError the operation requested
154 on the remote content is not permitted
155
156 \value ContentNotFoundError the remote content was not
157 found at the server (similar to HTTP error 404)
158
159 \value AuthenticationRequiredError the remote server requires
160 authentication to serve the content but the credentials provided
161 were not accepted (if any)
162
163 \value ContentReSendError the request needed to be sent
164 again, but this failed for example because the upload data
165 could not be read a second time.
166
167 \value ProtocolUnknownError the Network Access API cannot
168 honor the request because the protocol is not known
169
170 \value ProtocolInvalidOperationError the requested operation is
171 invalid for this protocol
172
173 \value UnknownNetworkError an unknown network-related
174 error was detected
175
176 \value UnknownProxyError an unknown proxy-related error
177 was detected
178
179 \value UnknownContentError an unknown error related to
180 the remote content was detected
181
182 \value ProtocolFailure a breakdown in protocol was
183 detected (parsing error, invalid or unexpected responses, etc.)
184
185 \sa error()
186*/
187
188/*!
189 \fn void QNetworkReply::sslErrors(const QList<QSslError> &errors)
190
191 This signal is emitted if the SSL/TLS session encountered errors
192 during the set up, including certificate verification errors. The
193 \a errors parameter contains the list of errors.
194
195 To indicate that the errors are not fatal and that the connection
196 should proceed, the ignoreSslErrors() function should be called
197 from the slot connected to this signal. If it is not called, the
198 SSL session will be torn down before any data is exchanged
199 (including the URL).
200
201 This signal can be used to display an error message to the user
202 indicating that security may be compromised and display the
203 SSL settings (see sslConfiguration() to obtain it). If the user
204 decides to proceed after analyzing the remote certificate, the
205 slot should call ignoreSslErrors().
206
207 \sa QSslSocket::sslErrors(), QNetworkAccessManager::sslErrors(),
208 sslConfiguration(), ignoreSslErrors()
209*/
210
211/*!
212 \fn void QNetworkReply::metaDataChanged()
213
214 \omit FIXME: Update name? \endomit
215
216 This signal is emitted whenever the metadata in this reply
217 changes. metadata is any information that is not the content
218 (data) itself, including the network headers. In the majority of
219 cases, the metadata will be known fully by the time the first
220 byte of data is received. However, it is possible to receive
221 updates of headers or other metadata during the processing of the
222 data.
223
224 \sa header(), rawHeaderList(), rawHeader(), hasRawHeader()
225*/
226
227/*!
228 \fn void QNetworkReply::finished()
229
230 This signal is emitted when the reply has finished
231 processing. After this signal is emitted, there will be no more
232 updates to the reply's data or metadata.
233
234 Unless close() has been called, the reply will be still be opened
235 for reading, so the data can be retrieved by calls to read() or
236 readAll(). In particular, if no calls to read() were made as a
237 result of readyRead(), a call to readAll() will retrieve the full
238 contents in a QByteArray.
239
240 This signal is emitted in tandem with
241 QNetworkAccessManager::finished() where that signal's reply
242 parameter is this object.
243
244 \note Do not delete the object in the slot connected to this
245 signal. Use deleteLater().
246
247 You can also use isFinished() to check if a QNetworkReply
248 has finished even before you receive the finished() signal.
249
250 \sa QNetworkAccessManager::finished(), isFinished()
251*/
252
253/*!
254 \fn void QNetworkReply::error(QNetworkReply::NetworkError code)
255
256 This signal is emitted when the reply detects an error in
257 processing. The finished() signal will probably follow, indicating
258 that the connection is over.
259
260 The \a code parameter contains the code of the error that was
261 detected. Call errorString() to obtain a textual representation of
262 the error condition.
263
264 \note Do not delete the object in the slot connected to this
265 signal. Use deleteLater().
266
267 \sa error(), errorString()
268*/
269
270/*!
271 \fn void QNetworkReply::uploadProgress(qint64 bytesSent, qint64 bytesTotal)
272
273 This signal is emitted to indicate the progress of the upload part
274 of this network request, if there's any. If there's no upload
275 associated with this request, this signal will not be emitted.
276
277 The \a bytesSent
278 parameter indicates the number of bytes uploaded, while \a
279 bytesTotal indicates the total number of bytes to be uploaded. If
280 the number of bytes to be uploaded could not be determined, \a
281 bytesTotal will be -1.
282
283 The upload is finished when \a bytesSent is equal to \a
284 bytesTotal. At that time, \a bytesTotal will not be -1.
285
286 \sa downloadProgress()
287*/
288
289/*!
290 \fn void QNetworkReply::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
291
292 This signal is emitted to indicate the progress of the download
293 part of this network request, if there's any. If there's no
294 download associated with this request, this signal will be emitted
295 once with 0 as the value of both \a bytesReceived and \a
296 bytesTotal.
297
298 The \a bytesReceived parameter indicates the number of bytes
299 received, while \a bytesTotal indicates the total number of bytes
300 expected to be downloaded. If the number of bytes to be downloaded
301 is not known, \a bytesTotal will be -1.
302
303 The download is finished when \a bytesReceived is equal to \a
304 bytesTotal. At that time, \a bytesTotal will not be -1.
305
306 Note that the values of both \a bytesReceived and \a bytesTotal
307 may be different from size(), the total number of bytes
308 obtained through read() or readAll(), or the value of the
309 header(ContentLengthHeader). The reason for that is that there may
310 be protocol overhead or the data may be compressed during the
311 download.
312
313 \sa uploadProgress(), bytesAvailable()
314*/
315
316/*!
317 \fn void QNetworkReply::abort()
318
319 Aborts the operation immediately and close down any network
320 connections still open. Uploads still in progress are also
321 aborted.
322
323 \sa close()
324*/
325
326/*!
327 Creates a QNetworkReply object with parent \a parent.
328
329 You cannot directly instantiate QNetworkReply objects. Use
330 QNetworkAccessManager functions to do that.
331*/
332QNetworkReply::QNetworkReply(QObject *parent)
333 : QIODevice(*new QNetworkReplyPrivate, parent)
334{
335}
336
337/*!
338 \internal
339*/
340QNetworkReply::QNetworkReply(QNetworkReplyPrivate &dd, QObject *parent)
341 : QIODevice(dd, parent)
342{
343}
344
345/*!
346 Disposes of this reply and frees any resources associated with
347 it. If any network connections are still open, they will be
348 closed.
349
350 \sa abort(), close()
351*/
352QNetworkReply::~QNetworkReply()
353{
354}
355
356/*!
357 Closes this device for reading. Unread data is discarded, but the
358 network resources are not discarded until they are finished. In
359 particular, if any upload is in progress, it will continue until
360 it is done.
361
362 The finished() signal is emitted when all operations are over and
363 the network resources are freed.
364
365 \sa abort(), finished()
366*/
367void QNetworkReply::close()
368{
369 QIODevice::close();
370}
371
372/*!
373 \internal
374*/
375bool QNetworkReply::isSequential() const
376{
377 return true;
378}
379
380/*!
381 Returns the size of the read buffer, in bytes.
382
383 \sa setReadBufferSize()
384*/
385qint64 QNetworkReply::readBufferSize() const
386{
387 return d_func()->readBufferMaxSize;
388}
389
390/*!
391 Sets the size of the read buffer to be \a size bytes. The read
392 buffer is the buffer that holds data that is being downloaded off
393 the network, before it is read with QIODevice::read(). Setting the
394 buffer size to 0 will make the buffer unlimited in size.
395
396 QNetworkReply will try to stop reading from the network once this
397 buffer is full (i.e., bytesAvailable() returns \a size or more),
398 thus causing the download to throttle down as well. If the buffer
399 is not limited in size, QNetworkReply will try to download as fast
400 as possible from the network.
401
402 Unlike QAbstractSocket::setReadBufferSize(), QNetworkReply cannot
403 guarantee precision in the read buffer size. That is,
404 bytesAvailable() can return more than \a size.
405
406 \sa readBufferSize()
407*/
408void QNetworkReply::setReadBufferSize(qint64 size)
409{
410 Q_D(QNetworkReply);
411 d->readBufferMaxSize = size;
412}
413
414/*!
415 Returns the QNetworkAccessManager that was used to create this
416 QNetworkReply object. Initially, it is also the parent object.
417*/
418QNetworkAccessManager *QNetworkReply::manager() const
419{
420 return d_func()->manager;
421}
422
423/*!
424 Returns the request that was posted for this reply. In special,
425 note that the URL for the request may be different than that of
426 the reply.
427
428 \sa QNetworkRequest::url(), url(), setRequest()
429*/
430QNetworkRequest QNetworkReply::request() const
431{
432 return d_func()->request;
433}
434
435/*!
436 Returns the operation that was posted for this reply.
437
438 \sa setOperation()
439*/
440QNetworkAccessManager::Operation QNetworkReply::operation() const
441{
442 return d_func()->operation;
443}
444
445/*!
446 Returns the error that was found during the processing of this
447 request. If no error was found, returns NoError.
448
449 \sa setError()
450*/
451QNetworkReply::NetworkError QNetworkReply::error() const
452{
453 return d_func()->errorCode;
454}
455
456/*!
457 \since 4.6
458
459 Returns true when the reply has finished or was aborted.
460
461 \sa isRunning()
462*/
463bool QNetworkReply::isFinished() const
464{
465 return d_func()->isFinished();
466}
467
468/*!
469 \since 4.6
470
471 Returns true when the request is still processing and the
472 reply has not finished or was aborted yet.
473
474 \sa isFinished()
475*/
476bool QNetworkReply::isRunning() const
477{
478 return !isFinished();
479}
480
481/*!
482 Returns the URL of the content downloaded or uploaded. Note that
483 the URL may be different from that of the original request.
484
485 \sa request(), setUrl(), QNetworkRequest::url()
486*/
487QUrl QNetworkReply::url() const
488{
489 return d_func()->url;
490}
491
492/*!
493 Returns the value of the known header \a header, if that header
494 was sent by the remote server. If the header was not sent, returns
495 an invalid QVariant.
496
497 \sa rawHeader(), setHeader(), QNetworkRequest::header()
498*/
499QVariant QNetworkReply::header(QNetworkRequest::KnownHeaders header) const
500{
501 return d_func()->cookedHeaders.value(header);
502}
503
504/*!
505 Returns true if the raw header of name \a headerName was sent by
506 the remote server
507
508 \sa rawHeader()
509*/
510bool QNetworkReply::hasRawHeader(const QByteArray &headerName) const
511{
512 Q_D(const QNetworkReply);
513 return d->findRawHeader(headerName) != d->rawHeaders.constEnd();
514}
515
516/*!
517 Returns the raw contents of the header \a headerName as sent by
518 the remote server. If there is no such header, returns an empty
519 byte array, which may be indistinguishable from an empty
520 header. Use hasRawHeader() to verify if the server sent such
521 header field.
522
523 \sa setRawHeader(), hasRawHeader(), header()
524*/
525QByteArray QNetworkReply::rawHeader(const QByteArray &headerName) const
526{
527 Q_D(const QNetworkReply);
528 QNetworkHeadersPrivate::RawHeadersList::ConstIterator it =
529 d->findRawHeader(headerName);
530 if (it != d->rawHeaders.constEnd())
531 return it->second;
532 return QByteArray();
533}
534
535/*! \typedef QNetworkReply::RawHeaderPair
536
537 RawHeaderPair is a QPair<QByteArray, QByteArray> where the first
538 QByteArray is the header name and the second is the header.
539 */
540
541/*!
542 Returns a list of raw header pairs.
543 */
544const QList<QNetworkReply::RawHeaderPair>& QNetworkReply::rawHeaderPairs() const
545{
546 Q_D(const QNetworkReply);
547 return d->rawHeaders;
548}
549
550/*!
551 Returns a list of headers fields that were sent by the remote
552 server, in the order that they were sent. Duplicate headers are
553 merged together and take place of the latter duplicate.
554*/
555QList<QByteArray> QNetworkReply::rawHeaderList() const
556{
557 return d_func()->rawHeadersKeys();
558}
559
560/*!
561 Returns the attribute associated with the code \a code. If the
562 attribute has not been set, it returns an invalid QVariant (type QVariant::Null).
563
564 You can expect the default values listed in
565 QNetworkRequest::Attribute to be applied to the values returned by
566 this function.
567
568 \sa setAttribute(), QNetworkRequest::Attribute
569*/
570QVariant QNetworkReply::attribute(QNetworkRequest::Attribute code) const
571{
572 return d_func()->attributes.value(code);
573}
574
575#ifndef QT_NO_OPENSSL
576/*!
577 Returns the SSL configuration and state associated with this
578 reply, if SSL was used. It will contain the remote server's
579 certificate, its certificate chain leading to the Certificate
580 Authority as well as the encryption ciphers in use.
581
582 The peer's certificate and its certificate chain will be known by
583 the time sslErrors() is emitted, if it's emitted.
584*/
585QSslConfiguration QNetworkReply::sslConfiguration() const
586{
587 QSslConfiguration config;
588
589 // determine if we support this extension
590 int id = metaObject()->indexOfMethod("sslConfigurationImplementation()");
591 if (id != -1) {
592 void *arr[] = { &config, 0 };
593 const_cast<QNetworkReply *>(this)->qt_metacall(QMetaObject::InvokeMetaMethod, id, arr);
594 }
595 return config;
596}
597
598/*!
599 Sets the SSL configuration for the network connection associated
600 with this request, if possible, to be that of \a config.
601*/
602void QNetworkReply::setSslConfiguration(const QSslConfiguration &config)
603{
604 if (config.isNull())
605 return;
606
607 int id = metaObject()->indexOfMethod("setSslConfigurationImplementation(QSslConfiguration)");
608 if (id != -1) {
609 QSslConfiguration copy(config);
610 void *arr[] = { 0, &copy };
611 qt_metacall(QMetaObject::InvokeMetaMethod, id, arr);
612 }
613}
614
615/*!
616 \overload
617 \since 4.6
618
619 If this function is called, the SSL errors given in \a errors
620 will be ignored.
621
622 Note that you can set the expected certificate in the SSL error:
623 If, for instance, you want to issue a request to a server that uses
624 a self-signed certificate, consider the following snippet:
625
626 \snippet doc/src/snippets/code/src_network_access_qnetworkreply.cpp 0
627
628 Multiple calls to this function will replace the list of errors that
629 were passed in previous calls.
630 You can clear the list of errors you want to ignore by calling this
631 function with an empty list.
632
633 \sa sslConfiguration(), sslErrors(), QSslSocket::ignoreSslErrors()
634*/
635void QNetworkReply::ignoreSslErrors(const QList<QSslError> &errors)
636{
637 // do this cryptic trick, because we could not add a virtual method to this class later on
638 // since that breaks binary compatibility
639 int id = metaObject()->indexOfMethod("ignoreSslErrorsImplementation(QList<QSslError>)");
640 if (id != -1) {
641 QList<QSslError> copy(errors);
642 void *arr[] = { 0, &copy };
643 qt_metacall(QMetaObject::InvokeMetaMethod, id, arr);
644 }
645}
646#endif
647
648/*!
649 If this function is called, SSL errors related to network
650 connection will be ignored, including certificate validation
651 errors.
652
653 Note that calling this function without restraint may pose a
654 security risk for your application. Use it with care.
655
656 This function can be called from the slot connected to the
657 sslErrors() signal, which indicates which errors were
658 found.
659
660 \sa sslConfiguration(), sslErrors(), QSslSocket::ignoreSslErrors()
661*/
662void QNetworkReply::ignoreSslErrors()
663{
664}
665
666/*!
667 \internal
668*/
669qint64 QNetworkReply::writeData(const char *, qint64)
670{
671 return -1; // you can't write
672}
673
674/*!
675 Sets the associated operation for this object to be \a
676 operation. This value will be returned by operation().
677
678 Note: the operation should be set when this object is created and
679 not changed again.
680
681 \sa operation(), setRequest()
682*/
683void QNetworkReply::setOperation(QNetworkAccessManager::Operation operation)
684{
685 Q_D(QNetworkReply);
686 d->operation = operation;
687}
688
689/*!
690 Sets the associated request for this object to be \a request. This
691 value will be returned by request().
692
693 Note: the request should be set when this object is created and
694 not changed again.
695
696 \sa request(), setOperation()
697*/
698void QNetworkReply::setRequest(const QNetworkRequest &request)
699{
700 Q_D(QNetworkReply);
701 d->request = request;
702}
703
704/*!
705 Sets the error condition to be \a errorCode. The human-readable
706 message is set with \a errorString.
707
708 Calling setError() does not emit the error(QNetworkReply::NetworkError)
709 signal.
710
711 \sa error(), errorString()
712*/
713void QNetworkReply::setError(NetworkError errorCode, const QString &errorString)
714{
715 Q_D(QNetworkReply);
716 d->errorCode = errorCode;
717 setErrorString(errorString); // in QIODevice
718}
719
720/*!
721 Sets the URL being processed to be \a url. Normally, the URL
722 matches that of the request that was posted, but for a variety of
723 reasons it can be different (for example, a file path being made
724 absolute or canonical).
725
726 \sa url(), request(), QNetworkRequest::url()
727*/
728void QNetworkReply::setUrl(const QUrl &url)
729{
730 Q_D(QNetworkReply);
731 d->url = url;
732}
733
734/*!
735 Sets the known header \a header to be of value \a value. The
736 corresponding raw form of the header will be set as well.
737
738 \sa header(), setRawHeader(), QNetworkRequest::setHeader()
739*/
740void QNetworkReply::setHeader(QNetworkRequest::KnownHeaders header, const QVariant &value)
741{
742 Q_D(QNetworkReply);
743 d->setCookedHeader(header, value);
744}
745
746/*!
747 Sets the raw header \a headerName to be of value \a value. If \a
748 headerName was previously set, it is overridden. Multiple HTTP
749 headers of the same name are functionally equivalent to one single
750 header with the values concatenated, separated by commas.
751
752 If \a headerName matches a known header, the value \a value will
753 be parsed and the corresponding parsed form will also be set.
754
755 \sa rawHeader(), header(), setHeader(), QNetworkRequest::setRawHeader()
756*/
757void QNetworkReply::setRawHeader(const QByteArray &headerName, const QByteArray &value)
758{
759 Q_D(QNetworkReply);
760 d->setRawHeader(headerName, value);
761}
762
763/*!
764 Sets the attribute \a code to have value \a value. If \a code was
765 previously set, it will be overridden. If \a value is an invalid
766 QVariant, the attribute will be unset.
767
768 \sa attribute(), QNetworkRequest::setAttribute()
769*/
770void QNetworkReply::setAttribute(QNetworkRequest::Attribute code, const QVariant &value)
771{
772 Q_D(QNetworkReply);
773 if (value.isValid())
774 d->attributes.insert(code, value);
775 else
776 d->attributes.remove(code);
777}
778
779QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.