KVIrc
4.9.2
DeveloperAPIs
|
The QHttp class provides an implementation of the HTTP protocol. More...
#include <qhttp.h>
Public Types | |
enum | ConnectionMode { ConnectionModeHttp, ConnectionModeHttps } |
enum | Error { NoError, UnknownError, HostNotFound, ConnectionRefused, UnexpectedClose, InvalidResponseHeader, WrongContentLength, Aborted, AuthenticationRequiredError, ProxyAuthenticationRequiredError } |
enum | State { Unconnected, HostLookup, Connecting, Sending, Reading, Connected, Closing } |
Public Slots | |
void | abort () |
void | ignoreSslErrors () |
Signals | |
void | authenticationRequired (const QString &hostname, quint16 port, QAuthenticator *) |
void | dataReadProgress (int, int) |
void | dataSendProgress (int, int) |
void | done (bool) |
void | proxyAuthenticationRequired (const QNetworkProxy &proxy, QAuthenticator *) |
void | readyRead (const QHttpResponseHeader &resp) |
void | requestFinished (int, bool) |
void | requestStarted (int) |
void | responseHeaderReceived (const QHttpResponseHeader &resp) |
void | sslErrors (const QList< QSslError > &errors) |
void | stateChanged (int) |
Public Member Functions | |
qint64 | bytesAvailable () const |
void | clearPendingRequests () |
int | close () |
int | closeConnection () |
QIODevice * | currentDestinationDevice () const |
int | currentId () const |
QHttpRequestHeader | currentRequest () const |
QIODevice * | currentSourceDevice () const |
Error | error () const |
QString | errorString () const |
int | get (const QString &path, QIODevice *to=0) |
bool | hasPendingRequests () const |
int | head (const QString &path) |
QHttpResponseHeader | lastResponse () const |
int | post (const QString &path, QIODevice *data, QIODevice *to=0) |
int | post (const QString &path, const QByteArray &data, QIODevice *to=0) |
QHttp (QObject *parent=0) | |
QHttp (const QString &hostname, quint16 port=80, QObject *parent=0) | |
QHttp (const QString &hostname, ConnectionMode mode, quint16 port=0, QObject *parent=0) | |
qint64 | read (char *data, qint64 maxlen) |
QByteArray | readAll () |
int | request (const QHttpRequestHeader &header, QIODevice *device=0, QIODevice *to=0) |
int | request (const QHttpRequestHeader &header, const QByteArray &data, QIODevice *to=0) |
int | setHost (const QString &hostname, quint16 port=80) |
int | setHost (const QString &hostname, ConnectionMode mode, quint16 port=0) |
int | setProxy (const QString &host, int port, const QString &username=QString(), const QString &password=QString()) |
int | setProxy (const QNetworkProxy &proxy) |
int | setSocket (QTcpSocket *socket) |
int | setUser (const QString &username, const QString &password=QString()) |
State | state () const |
virtual | ~QHttp () |
Private Member Functions | |
void | _q_continuePost () |
void | _q_slotBytesWritten (qint64 numBytes) |
void | _q_slotClosed () |
void | _q_slotConnected () |
void | _q_slotDoFinished () |
void | _q_slotEncryptedBytesWritten (qint64 numBytes) |
void | _q_slotError (QAbstractSocket::SocketError e) |
void | _q_slotReadyRead () |
void | _q_slotSendRequest () |
void | _q_startNextRequest () |
Private Attributes | |
QScopedPointer< QHttpPrivate > | d |
Friends | |
class | QHttpCloseRequest |
class | QHttpNormalRequest |
class | QHttpPGHRequest |
class | QHttpSetHostRequest |
class | QHttpSetProxyRequest |
class | QHttpSetSocketRequest |
class | QHttpSetUserRequest |
The QHttp class provides an implementation of the HTTP protocol.
QtNetwork
This class provides a direct interface to HTTP that allows you to download and upload data with the HTTP protocol. However, for new applications, it is recommended to use QNetworkAccessManager and QNetworkReply, as those classes possess a simpler, yet more powerful API and a more modern protocol implementation.
The class works asynchronously, so there are no blocking functions. If an operation cannot be executed immediately, the function will still return straight away and the operation will be scheduled for later execution. The results of scheduled operations are reported via signals. This approach depends on the event loop being in operation.
The operations that can be scheduled (they are called "requests" in the rest of the documentation) are the following: setHost(), get(), post(), head() and request().
All of these requests return a unique identifier that allows you to keep track of the request that is currently executed. When the execution of a request starts, the requestStarted() signal with the identifier is emitted and when the request is finished, the requestFinished() signal is emitted with the identifier and a bool that indicates if the request finished with an error.
To make an HTTP request you must set up suitable HTTP headers. The following example demonstrates how to request the main HTML page from the Qt website (i.e., the URL http://qt.digia.com/index.html
):
For the common HTTP requests GET
, POST
and HEAD
, QHttp provides the convenience functions get(), post() and head(). They already use a reasonable header and if you don't have to set special header fields, they are easier to use. The above example can also be written as:
For this example the following sequence of signals is emitted (with small variations, depending on network traffic, etc.):
The dataSendProgress() and dataReadProgress() signals in the above example are useful if you want to show a progress bar to inform the user about the progress of the download. The second argument is the total size of data. In certain cases it is not possible to know the total amount in advance, in which case the second argument is 0. (If you connect to a QProgressBar a total of 0 results in a busy indicator.)
When the response header is read, it is reported with the responseHeaderReceived() signal.
The readyRead() signal tells you that there is data ready to be read. The amount of data can then be queried with the bytesAvailable() function and it can be read with the read() or readAll() functions.
If an error occurs during the execution of one of the commands in a sequence of commands, all the pending commands (i.e. scheduled, but not yet executed commands) are cleared and no signals are emitted for them.
For example, if you have the following sequence of requests
and the get() request fails because the host lookup fails, then the post() request is never executed and the signals would look like this:
You can then get details about the error with the error() and errorString() functions. Note that only unexpected behavior, like network failure is considered as an error. If the server response contains an error status, like a 404 response, this is reported as a normal response case. So you should always check the status code of the response header.
The functions currentId() and currentRequest() provide more information about the currently executing request.
The functions hasPendingRequests() and clearPendingRequests() allow you to query and clear the list of pending requests.
This enum is used to specify the mode of connection to use:
ConnectionModeHttp The connection is a regular HTTP connection to the server ConnectionModeHttps The HTTPS protocol is used and the connection is encrypted using SSL.
When using the HTTPS mode, care should be taken to connect to the sslErrors signal, and handle possible SSL errors.
Enumerator | |
---|---|
ConnectionModeHttp | |
ConnectionModeHttps |
enum QHttp::Error |
This enum identifies the error that occurred.
NoError No error occurred. HostNotFound The host name lookup failed. ConnectionRefused The server refused the connection. UnexpectedClose The server closed the connection unexpectedly. InvalidResponseHeader The server sent an invalid response header. WrongContentLength The client could not read the content correctly because an error with respect to the content length occurred. Aborted The request was aborted with abort(). ProxyAuthenticationRequiredError QHttp is using a proxy, and the proxy server requires authentication to establish a connection. AuthenticationRequiredError The web server requires authentication to complete the request. UnknownError An error other than those specified above occurred.
Enumerator | |
---|---|
NoError | |
UnknownError | |
HostNotFound | |
ConnectionRefused | |
UnexpectedClose | |
InvalidResponseHeader | |
WrongContentLength | |
Aborted | |
AuthenticationRequiredError | |
ProxyAuthenticationRequiredError |
enum QHttp::State |
This enum is used to specify the state the client is in:
Unconnected There is no connection to the host. HostLookup A host name lookup is in progress. Connecting An attempt to connect to the host is in progress. Sending The client is sending its request to the server. Reading The client's request has been sent and the client is reading the server's response. Connected The connection to the host is open, but the client is neither sending a request, nor waiting for a response. Closing The connection is closing down, but is not yet closed. (The state will be Unconnected
when the connection is closed.)
Enumerator | |
---|---|
Unconnected | |
HostLookup | |
Connecting | |
Sending | |
Reading | |
Connected | |
Closing |
|
explicit |
QHttp::QHttp | ( | const QString & | hostName, |
quint16 | port = 80 , |
||
QObject * | parent = 0 |
||
) |
QHttp::QHttp | ( | const QString & | hostName, |
ConnectionMode | mode, | ||
quint16 | port = 0 , |
||
QObject * | parent = 0 |
||
) |
Constructs a QHttp object. Subsequent requests are done by connecting to the server hostName on port port using the connection mode mode.
If port is 0, it will use the default port for the mode used (80 for Http and 443 for Https).
The parent parameter is passed on to the QObject constructor.
References ConnectionModeHttp, and d.
|
virtual |
|
private |
References d.
|
private |
References d.
|
private |
References d.
|
private |
References d.
|
private |
References d.
|
private |
References d.
|
private |
References d.
|
private |
References d.
|
private |
References d.
|
private |
References d.
|
slot |
Aborts the current request and deletes all scheduled requests.
For the current request, the requestFinished() signal with the error
argument true
is emitted. For all other requests that are affected by the abort(), no signals are emitted.
Since this slot also deletes the scheduled requests, there are no requests left and the done() signal is emitted (with the error
argument true
).
References Aborted, clearPendingRequests(), and d.
Referenced by ~QHttp().
|
signal |
This signal can be emitted when a web server on a given hostname and port requires authentication. The authenticator object can then be filled in with the required details to allow authentication and continue the connection.
qint64 QHttp::bytesAvailable | ( | ) | const |
void QHttp::clearPendingRequests | ( | ) |
Deletes all pending requests from the list of scheduled requests. This does not affect the request that is being executed. If you want to stop this as well, use abort().
References d.
Referenced by abort().
int QHttp::close | ( | ) |
Closes the connection; this is useful if you have a keep-alive connection and want to close it.
For the requests issued with get(), post() and head(), QHttp sets the connection to be keep-alive. You can also do this using the header you pass to the request() function. QHttp only closes the connection to the HTTP server if the response header requires it to do so.
The function does not block; instead, it returns immediately. The request is scheduled, and its execution is performed asynchronously. The function returns a unique identifier which is passed by requestStarted() and requestFinished().
When the request is started the requestStarted() signal is emitted. When it is finished the requestFinished() signal is emitted.
If you want to close the connection immediately, you have to use abort() instead.
References d, and QHttpCloseRequest.
int QHttp::closeConnection | ( | ) |
Behaves the same as close().
References d, and QHttpCloseRequest.
QIODevice * QHttp::currentDestinationDevice | ( | ) | const |
Returns the QIODevice pointer that is used as to store the data of the HTTP request being executed. If there is no current request or if the request does not store the data to an IO device, this function returns 0.
This function can be used to delete the QIODevice in the slot connected to the requestFinished() signal.
References d.
int QHttp::currentId | ( | ) | const |
Returns the identifier of the HTTP request being executed or 0 if there is no request being executed (i.e. they've all finished).
References d.
QHttpRequestHeader QHttp::currentRequest | ( | ) | const |
Returns the request header of the HTTP request being executed. If the request is one issued by setHost() or close(), it returns an invalid request header, i.e. QHttpRequestHeader::isValid() returns false.
References d, QHttpRequest::hasRequestHeader(), r, and QHttpRequest::requestHeader().
QIODevice * QHttp::currentSourceDevice | ( | ) | const |
Returns the QIODevice pointer that is used as the data source of the HTTP request being executed. If there is no current request or if the request does not use an IO device as the data source, this function returns 0.
This function can be used to delete the QIODevice in the slot connected to the requestFinished() signal.
References d.
|
signal |
This signal is emitted when this object reads data from a HTTP server to indicate the current progress of the download.
done is the amount of data that has already arrived and total is the total amount of data. It is possible that the total amount of data that should be transferred cannot be determined, in which case total is 0.(If you connect to a QProgressBar, the progress bar shows a busy indicator if the total is 0).
|
signal |
This signal is emitted when this object sends data to a HTTP server to inform it about the progress of the upload.
done is the amount of data that has already arrived and total is the total amount of data. It is possible that the total amount of data that should be transferred cannot be determined, in which case total is 0.(If you connect to a QProgressBar, the progress bar shows a busy indicator if the total is 0).
|
signal |
This signal is emitted when the last pending request has finished; (it is emitted after the last request's requestFinished() signal). error is true if an error occurred during the processing; otherwise error is false.
QHttp::Error QHttp::error | ( | ) | const |
Returns the last error that occurred. This is useful to find out what happened when receiving a requestFinished() or a done() signal with the error
argument true
.
If you start a new request, the error status is reset to NoError
.
References d.
QString QHttp::errorString | ( | ) | const |
Returns a human-readable description of the last error that occurred. This is useful to present a error message to the user when receiving a requestFinished() or a done() signal with the error
argument true
.
References d.
int QHttp::get | ( | const QString & | path, |
QIODevice * | to = 0 |
||
) |
Sends a get request for path to the server set by setHost() or as specified in the constructor.
path must be a absolute path like /index
.html or an absolute URI like http://example.com/index.html
and must be encoded with either QUrl::toPercentEncoding() or QUrl::encodedPath().
If the IO device to is 0 the readyRead() signal is emitted every time new content data is available to read.
If the IO device to is not 0, the content data of the response is written directly to the device. Make sure that the to pointer is valid for the duration of the operation (it is safe to delete it when the requestFinished() signal is emitted).
References d, QHttpPGHRequest, and QHttpHeader::setValue().
bool QHttp::hasPendingRequests | ( | ) | const |
Returns true if there are any requests scheduled that have not yet been executed; otherwise returns false.
The request that is being executed is not considered as a scheduled request.
References d.
int QHttp::head | ( | const QString & | path | ) |
Sends a header request for path to the server set by setHost() or as specified in the constructor.
path must be an absolute path like /index
.html or an absolute URI like http://example.com/index.html
.
The function does not block; instead, it returns immediately. The request is scheduled, and its execution is performed asynchronously. The function returns a unique identifier which is passed by requestStarted() and requestFinished().
When the request is started the requestStarted() signal is emitted. When it is finished the requestFinished() signal is emitted.
References d, QHttpPGHRequest, and QHttpHeader::setValue().
|
slot |
Tells the QSslSocket used for the Http connection to ignore the errors reported in the sslErrors() signal.
Note that this function must be called from within a slot connected to the sslErrors() signal to have any effect.
References d.
QHttpResponseHeader QHttp::lastResponse | ( | ) | const |
Returns the received response header of the most recently finished HTTP request. If no response has yet been received QHttpResponseHeader::isValid() will return false.
References d.
int QHttp::post | ( | const QString & | path, |
QIODevice * | data, | ||
QIODevice * | to = 0 |
||
) |
Sends a post request for path to the server set by setHost() or as specified in the constructor.
path must be an absolute path like /index
.html or an absolute URI like http://example.com/index.html
and must be encoded with either QUrl::toPercentEncoding() or QUrl::encodedPath().
The incoming data comes via the data IO device.
If the IO device to is 0 the readyRead() signal is emitted every time new content data is available to read.
If the IO device to is not 0, the content data of the response is written directly to the device. Make sure that the to pointer is valid for the duration of the operation (it is safe to delete it when the requestFinished() signal is emitted).
The function does not block; instead, it returns immediately. The request is scheduled, and its execution is performed asynchronously. The function returns a unique identifier which is passed by requestStarted() and requestFinished().
When the request is started the requestStarted() signal is emitted. When it is finished the requestFinished() signal is emitted.
References d, QHttpPGHRequest, and QHttpHeader::setValue().
int QHttp::post | ( | const QString & | path, |
const QByteArray & | data, | ||
QIODevice * | to = 0 |
||
) |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
data is used as the content data of the HTTP request.
References d, QHttpPGHRequest, and QHttpHeader::setValue().
|
signal |
This signal can be emitted when a proxy that requires authentication is used. The authenticator object can then be filled in with the required details to allow authentication and continue the connection.
qint64 QHttp::read | ( | char * | data, |
qint64 | maxlen | ||
) |
QByteArray QHttp::readAll | ( | ) |
Reads all the bytes from the response content and returns them.
References bytesAvailable(), and read().
|
signal |
This signal is emitted when there is new response data to read.
If you specified a device in the request where the data should be written to, then this signal is not emitted; instead the data is written directly to the device.
The response header is passed in resp.
You can read the data with the readAll() or read() functions
This signal is useful if you want to process the data in chunks as soon as it becomes available. If you are only interested in the complete data, just connect to the requestFinished() signal and read the data then instead.
int QHttp::request | ( | const QHttpRequestHeader & | header, |
QIODevice * | data = 0 , |
||
QIODevice * | to = 0 |
||
) |
Sends a request to the server set by setHost() or as specified in the constructor. Uses the header as the HTTP request header. You are responsible for setting up a header that is appropriate for your request.
The incoming data comes via the data IO device.
If the IO device to is 0 the readyRead() signal is emitted every time new content data is available to read.
If the IO device to is not 0, the content data of the response is written directly to the device. Make sure that the to pointer is valid for the duration of the operation (it is safe to delete it when the requestFinished() signal is emitted).
The function does not block; instead, it returns immediately. The request is scheduled, and its execution is performed asynchronously. The function returns a unique identifier which is passed by requestStarted() and requestFinished().
When the request is started the requestStarted() signal is emitted. When it is finished the requestFinished() signal is emitted.
References d, and QHttpNormalRequest.
int QHttp::request | ( | const QHttpRequestHeader & | header, |
const QByteArray & | data, | ||
QIODevice * | to = 0 |
||
) |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
data is used as the content data of the HTTP request.
References d, and QHttpNormalRequest.
|
signal |
This signal is emitted when processing the request identified by id has finished. error is true if an error occurred during the processing; otherwise error is false.
|
signal |
This signal is emitted when processing the request identified by id starts.
|
signal |
This signal is emitted when the HTTP header of a server response is available. The header is passed in resp.
int QHttp::setHost | ( | const QString & | hostName, |
quint16 | port = 80 |
||
) |
Sets the HTTP server that is used for requests to hostName on port port.
The function does not block; instead, it returns immediately. The request is scheduled, and its execution is performed asynchronously. The function returns a unique identifier which is passed by requestStarted() and requestFinished().
When the request is started the requestStarted() signal is emitted. When it is finished the requestFinished() signal is emitted.
References ConnectionModeHttp, d, and QHttpSetHostRequest.
int QHttp::setHost | ( | const QString & | hostName, |
ConnectionMode | mode, | ||
quint16 | port = 0 |
||
) |
Sets the HTTP server that is used for requests to hostName on port port using the connection mode mode.
If port is 0, it will use the default port for the mode used (80 for HTTP and 443 for HTTPS).
The function does not block; instead, it returns immediately. The request is scheduled, and its execution is performed asynchronously. The function returns a unique identifier which is passed by requestStarted() and requestFinished().
When the request is started the requestStarted() signal is emitted. When it is finished the requestFinished() signal is emitted.
References ConnectionModeHttp, ConnectionModeHttps, d, and QHttpSetHostRequest.
int QHttp::setProxy | ( | const QString & | host, |
int | port, | ||
const QString & | username = QString() , |
||
const QString & | password = QString() |
||
) |
Enables HTTP proxy support, using the proxy server host on port port. username and password can be provided if the proxy server requires authentication.
Example:
QHttp supports non-transparent web proxy servers only, such as the Squid Web proxy cache server (from http://www.squid.org/). For transparent proxying, such as SOCKS5, use QNetworkProxy instead.
References d, and QHttpSetProxyRequest.
int QHttp::setProxy | ( | const QNetworkProxy & | proxy | ) |
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
Enables HTTP proxy support using the proxy settings from proxy. If proxy is a transparent proxy, QHttp will call QAbstractSocket::setProxy() on the underlying socket. If the type is QNetworkProxy::HttpCachingProxy, QHttp will behave like the previous function.
References d, and QHttpSetProxyRequest.
int QHttp::setSocket | ( | QTcpSocket * | socket | ) |
Replaces the internal QTcpSocket that QHttp uses with socket. This is useful if you want to use your own custom QTcpSocket subclass instead of the plain QTcpSocket that QHttp uses by default. QHttp does not take ownership of the socket, and will not delete socket when destroyed.
The function does not block; instead, it returns immediately. The request is scheduled, and its execution is performed asynchronously. The function returns a unique identifier which is passed by requestStarted() and requestFinished().
When the request is started the requestStarted() signal is emitted. When it is finished the requestFinished() signal is emitted.
Note: If QHttp is used in a non-GUI thread that runs its own event loop, you must move socket to that thread before calling setSocket().
References d, and QHttpSetSocketRequest.
int QHttp::setUser | ( | const QString & | userName, |
const QString & | password = QString() |
||
) |
This function sets the user name userName and password password for web pages that require authentication.
The function does not block; instead, it returns immediately. The request is scheduled, and its execution is performed asynchronously. The function returns a unique identifier which is passed by requestStarted() and requestFinished().
When the request is started the requestStarted() signal is emitted. When it is finished the requestFinished() signal is emitted.
References d, and QHttpSetUserRequest.
|
signal |
Forwards the sslErrors signal from the QSslSocket used in QHttp. errors is the list of errors that occurred during the SSL handshake. Unless you call ignoreSslErrors() from within a slot connected to this signal when an error occurs, QHttp will tear down the connection immediately after emitting the signal.
QHttp::State QHttp::state | ( | ) | const |
Returns the current state of the object. When the state changes, the stateChanged() signal is emitted.
References d.
|
signal |
|
friend |
Referenced by close(), and closeConnection().
|
friend |
Referenced by request().
|
friend |
|
friend |
Referenced by setHost().
|
friend |
Referenced by setProxy().
|
friend |
Referenced by setSocket().
|
friend |
Referenced by setUser().
|
private |
Referenced by _q_continuePost(), _q_slotBytesWritten(), _q_slotClosed(), _q_slotConnected(), _q_slotDoFinished(), _q_slotEncryptedBytesWritten(), _q_slotError(), _q_slotReadyRead(), _q_slotSendRequest(), _q_startNextRequest(), abort(), bytesAvailable(), clearPendingRequests(), close(), closeConnection(), currentDestinationDevice(), currentId(), currentRequest(), currentSourceDevice(), get(), hasPendingRequests(), head(), lastResponse(), post(), QHttp(), read(), request(), setHost(), setProxy(), setSocket(), setUser(), QHttpNormalRequest::start(), QHttpPGHRequest::start(), QHttpSetHostRequest::start(), QHttpSetUserRequest::start(), QHttpSetProxyRequest::start(), QHttpSetSocketRequest::start(), and QHttpCloseRequest::start().