
We bake cookies in your browser for a better experience. Using this site means that you consent.Read More
TheQHttp class provides an implementation of the HTTP protocol.More...
| Header: | #include <QHttp> |
| Inherits: | QObject |
This class is obsolete. It is provided to keep old source code working. We strongly advise against using it in new code.
Note: All functions in this class arereentrant.
| enum | ConnectionMode { ConnectionModeHttp, ConnectionModeHttps } |
| enum | Error { NoError, HostNotFound, ConnectionRefused, UnexpectedClose, ..., UnknownError } |
| enum | State { Unconnected, HostLookup, Connecting, Sending, ..., Closing } |
| 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) | |
| virtual | ~QHttp() |
| qint64 | bytesAvailable() const |
| void | clearPendingRequests() |
| int | close() |
| 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) |
| qint64 | read(char * data, qint64 maxlen) |
| QByteArray | readAll() |
| int | request(const QHttpRequestHeader & header, QIODevice * data = 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 |
| void | abort() |
| void | ignoreSslErrors() |
| void | authenticationRequired(const QString & hostname, quint16 port, QAuthenticator * authenticator) |
| void | dataReadProgress(int done, int total) |
| void | dataSendProgress(int done, int total) |
| void | done(bool error) |
| void | proxyAuthenticationRequired(const QNetworkProxy & proxy, QAuthenticator * authenticator) |
| void | readyRead(const QHttpResponseHeader & resp) |
| void | requestFinished(int id, bool error) |
| void | requestStarted(int id) |
| void | responseHeaderReceived(const QHttpResponseHeader & resp) |
| void | sslErrors(const QList<QSslError> & errors) |
| void | stateChanged(int state) |
TheQHttp class provides an implementation of the HTTP protocol.
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 useQNetworkAccessManager andQNetworkReply, 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() andrequest().
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, therequestStarted() signal with the identifier is emitted and when the request is finished, therequestFinished() 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 URLhttp://www.qt.io):
QHttpRequestHeader header("GET",QUrl::toPercentEncoding("/index.html"));header.setValue("Host","qt.nokia.com");http->setHost("qt.nokia.com");http->request(header);
For the common HTTP requestsGET,POST andHEAD,QHttp provides the convenience functionsget(),post() andhead(). 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:
http->setHost("qt.nokia.com");// id == 1http->get(QUrl::toPercentEncoding("/index.html"));// id == 2
For this example the following sequence of signals is emitted (with small variations, depending on network traffic, etc.):
requestStarted(1)requestFinished(1,false)requestStarted(2)stateChanged(Connecting)stateChanged(Sending)dataSendProgress(77,77)stateChanged(Reading)responseHeaderReceived(responseheader)dataReadProgress(5388,0)readyRead(responseheader)dataReadProgress(18300,0)readyRead(responseheader)stateChanged(Connected)requestFinished(2,false)done(false)stateChanged(Closing)stateChanged(Unconnected)
ThedataSendProgress() anddataReadProgress() signals in the above example are useful if you want to show aprogress 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 aQProgressBar a total of 0 results in a busy indicator.)
When the response header is read, it is reported with theresponseHeaderReceived() signal.
ThereadyRead() signal tells you that there is data ready to be read. The amount of data can then be queried with thebytesAvailable() function and it can be read with theread() orreadAll() 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
http->setHost("www.foo.bar");// id == 1http->get("/index.html");// id == 2http->post("register.html", data);// id == 3
and theget() request fails because the host lookup fails, then thepost() request is never executed and the signals would look like this:
requestStarted(1)requestFinished(1,false)requestStarted(2)stateChanged(HostLookup)requestFinished(2,true)done(true)stateChanged(Unconnected)
You can then get details about the error with theerror() anderrorString() 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 thestatus code of the response header.
The functionscurrentId() andcurrentRequest() provide more information about the currently executing request.
The functionshasPendingRequests() andclearPendingRequests() allow you to query and clear the list of pending requests.
See alsoQFtp,QNetworkAccessManager,QNetworkRequest,QNetworkReply,HTTP Example, andTorrent Example.
This enum is used to specify the mode of connection to use:
| Constant | Value | Description |
|---|---|---|
QHttp::ConnectionModeHttp | 0 | The connection is a regular HTTP connection to the server |
QHttp::ConnectionModeHttps | 1 | The HTTPS protocol is used and the connection is encrypted using SSL. |
When using the HTTPS mode, care should be taken to connect to thesslErrors signal, and handle possible SSL errors.
This enum was introduced or modified in Qt 4.3.
See alsoQSslSocket.
This enum identifies the error that occurred.
| Constant | Value | Description |
|---|---|---|
QHttp::NoError | 0 | No error occurred. |
QHttp::HostNotFound | 2 | The host name lookup failed. |
QHttp::ConnectionRefused | 3 | The server refused the connection. |
QHttp::UnexpectedClose | 4 | The server closed the connection unexpectedly. |
QHttp::InvalidResponseHeader | 5 | The server sent an invalid response header. |
QHttp::WrongContentLength | 6 | The client could not read the content correctly because an error with respect to the content length occurred. |
QHttp::Aborted | 7 | The request was aborted withabort(). |
QHttp::ProxyAuthenticationRequiredError | 9 | QHttp is using a proxy, and the proxy server requires authentication to establish a connection. |
QHttp::AuthenticationRequiredError | 8 | The web server requires authentication to complete the request. |
QHttp::UnknownError | 1 | An error other than those specified above occurred. |
See alsoerror().
This enum is used to specify the state the client is in:
| Constant | Value | Description |
|---|---|---|
QHttp::Unconnected | 0 | There is no connection to the host. |
QHttp::HostLookup | 1 | A host name lookup is in progress. |
QHttp::Connecting | 2 | An attempt to connect to the host is in progress. |
QHttp::Sending | 3 | The client is sending its request to the server. |
QHttp::Reading | 4 | The client's request has been sent and the client is reading the server's response. |
QHttp::Connected | 5 | The connection to the host is open, but the client is neither sending a request, nor waiting for a response. |
QHttp::Closing | 6 | The connection is closing down, but is not yet closed. (The state will beUnconnected when the connection is closed.) |
See alsostateChanged() andstate().
Constructs aQHttp object. Theparent parameter is passed on to theQObject constructor.
Constructs aQHttp object. Subsequent requests are done by connecting to the serverhostName on portport.
Theparent parameter is passed on to theQObject constructor.
See alsosetHost().
Constructs aQHttp object. Subsequent requests are done by connecting to the serverhostName on portport using the connection modemode.
If port is 0, it will use the default port for themode used (80 for Http and 443 for Https).
Theparent parameter is passed on to theQObject constructor.
See alsosetHost().
[virtual]QHttp::~QHttp()Destroys theQHttp object. If there is an open connection, it is closed.
[slot]void QHttp::abort()Aborts the current request and deletes all scheduled requests.
For the current request, therequestFinished() signal with theerror argumenttrue 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 thedone() signal is emitted (with theerror argumenttrue).
See alsoclearPendingRequests().
[signal]void QHttp::authenticationRequired(constQString & hostname,quint16 port,QAuthenticator * authenticator)This signal can be emitted when a web server on a givenhostname andport requires authentication. Theauthenticator object can then be filled in with the required details to allow authentication and continue the connection.
Note:It is not possible to use a QueuedConnection to connect to this signal, as the connection will fail if the authenticator has not been filled in with new information when the signal returns.
This function was introduced in Qt 4.3.
See alsoQAuthenticator andQNetworkProxy.
Returns the number of bytes that can be read from the response content at the moment.
See alsoget(),post(),request(),readyRead(),read(), andreadAll().
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, useabort().
See alsohasPendingRequests() andabort().
Closes the connection; this is useful if you have a keep-alive connection and want to close it.
For the requests issued withget(),post() andhead(),QHttp sets the connection to be keep-alive. You can also do this using the header you pass to therequest() 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 byrequestStarted() andrequestFinished().
When the request is started therequestStarted() signal is emitted. When it is finished therequestFinished() signal is emitted.
If you want to close the connection immediately, you have to useabort() instead.
See alsostateChanged(),abort(),requestStarted(),requestFinished(), anddone().
Returns theQIODevice 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 theQIODevice in the slot connected to therequestFinished() signal.
See alsocurrentSourceDevice(),get(),post(), andrequest().
Returns the identifier of the HTTP request being executed or 0 if there is no request being executed (i.e. they've all finished).
See alsocurrentRequest().
Returns the request header of the HTTP request being executed. If the request is one issued bysetHost() orclose(), it returns an invalid request header, i.e.QHttpRequestHeader::isValid() returns false.
See alsocurrentId().
Returns theQIODevice 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 theQIODevice in the slot connected to therequestFinished() signal.
See alsocurrentDestinationDevice(),post(), andrequest().
[signal]void QHttp::dataReadProgress(int done,int total)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 andtotal is the total amount of data. It is possible that the total amount of data that should be transferred cannot be determined, in which casetotal is 0.(If you connect to aQProgressBar, the progress bar shows a busy indicator if the total is 0).
Warning:done andtotal are not necessarily the size in bytes, since for large files these values might need to be "scaled" to avoid overflow.
See alsodataSendProgress(),get(),post(),request(), andQProgressBar.
[signal]void QHttp::dataSendProgress(int done,int total)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 andtotal is the total amount of data. It is possible that the total amount of data that should be transferred cannot be determined, in which casetotal is 0.(If you connect to aQProgressBar, the progress bar shows a busy indicator if the total is 0).
Warning:done andtotal are not necessarily the size in bytes, since for large files these values might need to be "scaled" to avoid overflow.
See alsodataReadProgress(),post(),request(), andQProgressBar.
[signal]void QHttp::done(bool error)This signal is emitted when the last pending request has finished; (it is emitted after the last request'srequestFinished() signal).error is true if an error occurred during the processing; otherwiseerror is false.
See alsorequestFinished(),error(), anderrorString().
Returns the last error that occurred. This is useful to find out what happened when receiving arequestFinished() or adone() signal with theerror argumenttrue.
If you start a new request, the error status is reset toNoError.
Returns a human-readable description of the last error that occurred. This is useful to present a error message to the user when receiving arequestFinished() or adone() signal with theerror argumenttrue.
Sends a get request forpath to the server set bysetHost() or as specified in the constructor.
path must be a absolute path like/index.html or an absolute URI likehttp://example.com/index.html and must be encoded with eitherQUrl::toPercentEncoding() orQUrl::encodedPath().
If the IO deviceto is 0 thereadyRead() signal is emitted every time new content data is available to read.
If the IO deviceto is not 0, the content data of the response is written directly to the device. Make sure that theto pointer is valid for the duration of the operation (it is safe to delete it when therequestFinished() 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 byrequestStarted() andrequestFinished().
When the request is started therequestStarted() signal is emitted. When it is finished therequestFinished() signal is emitted.
See alsosetHost(),post(),head(),request(),requestStarted(),requestFinished(), anddone().
Returns true if there are any requests scheduled that have not yet been executed; otherwise returns false.
The request that is being executed isnot considered as a scheduled request.
See alsoclearPendingRequests(),currentId(), andcurrentRequest().
Sends a header request forpath to the server set bysetHost() or as specified in the constructor.
path must be an absolute path like/index.html or an absolute URI likehttp://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 byrequestStarted() andrequestFinished().
When the request is started therequestStarted() signal is emitted. When it is finished therequestFinished() signal is emitted.
See alsosetHost(),get(),post(),request(),requestStarted(),requestFinished(), anddone().
[slot]void QHttp::ignoreSslErrors()Tells theQSslSocket used for the Http connection to ignore the errors reported in thesslErrors() signal.
Note that this function must be called from within a slot connected to thesslErrors() signal to have any effect.
See alsoQSslSocket andQSslSocket::sslErrors().
Returns the received response header of the most recently finished HTTP request. If no response has yet been receivedQHttpResponseHeader::isValid() will return false.
See alsocurrentRequest().
Sends a post request forpath to the server set bysetHost() or as specified in the constructor.
path must be an absolute path like/index.html or an absolute URI likehttp://example.com/index.html and must be encoded with eitherQUrl::toPercentEncoding() orQUrl::encodedPath().
The incoming data comes via thedata IO device.
If the IO deviceto is 0 thereadyRead() signal is emitted every time new content data is available to read.
If the IO deviceto is not 0, the content data of the response is written directly to the device. Make sure that theto pointer is valid for the duration of the operation (it is safe to delete it when therequestFinished() 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 byrequestStarted() andrequestFinished().
When the request is started therequestStarted() signal is emitted. When it is finished therequestFinished() signal is emitted.
See alsosetHost(),get(),head(),request(),requestStarted(),requestFinished(), anddone().
This is an overloaded function.
data is used as the content data of the HTTP request.
[signal]void QHttp::proxyAuthenticationRequired(constQNetworkProxy & proxy,QAuthenticator * authenticator)This signal can be emitted when aproxy that requires authentication is used. Theauthenticator object can then be filled in with the required details to allow authentication and continue the connection.
Note:It is not possible to use a QueuedConnection to connect to this signal, as the connection will fail if the authenticator has not been filled in with new information when the signal returns.
This function was introduced in Qt 4.3.
See alsoQAuthenticator andQNetworkProxy.
Readsmaxlen bytes from the response content intodata and returns the number of bytes read. Returns -1 if an error occurred.
See alsoget(),post(),request(),readyRead(),bytesAvailable(), andreadAll().
Reads all the bytes from the response content and returns them.
See alsoget(),post(),request(),readyRead(),bytesAvailable(), andread().
[signal]void QHttp::readyRead(constQHttpResponseHeader & resp)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 isnot emitted; instead the data is written directly to the device.
The response header is passed inresp.
You can read the data with thereadAll() orread() 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 therequestFinished() signal and read the data then instead.
See alsoget(),post(),request(),readAll(),read(), andbytesAvailable().
Sends a request to the server set bysetHost() or as specified in the constructor. Uses theheader as the HTTP request header. You are responsible for setting up a header that is appropriate for your request.
The incoming data comes via thedata IO device.
If the IO deviceto is 0 thereadyRead() signal is emitted every time new content data is available to read.
If the IO deviceto is not 0, the content data of the response is written directly to the device. Make sure that theto pointer is valid for the duration of the operation (it is safe to delete it when therequestFinished() 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 byrequestStarted() andrequestFinished().
When the request is started therequestStarted() signal is emitted. When it is finished therequestFinished() signal is emitted.
See alsosetHost(),get(),post(),head(),requestStarted(),requestFinished(), anddone().
This is an overloaded function.
data is used as the content data of the HTTP request.
[signal]void QHttp::requestFinished(int id,bool error)This signal is emitted when processing the request identified byid has finished.error is true if an error occurred during the processing; otherwiseerror is false.
See alsorequestStarted(),done(),error(), anderrorString().
[signal]void QHttp::requestStarted(int id)This signal is emitted when processing the request identified byid starts.
See alsorequestFinished() anddone().
[signal]void QHttp::responseHeaderReceived(constQHttpResponseHeader & resp)This signal is emitted when the HTTP header of a server response is available. The header is passed inresp.
See alsoget(),post(),head(),request(), andreadyRead().
Sets the HTTP server that is used for requests tohostName on portport.
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 byrequestStarted() andrequestFinished().
When the request is started therequestStarted() signal is emitted. When it is finished therequestFinished() signal is emitted.
See alsoget(),post(),head(),request(),requestStarted(),requestFinished(), anddone().
Sets the HTTP server that is used for requests tohostName on portport using the connection modemode.
If port is 0, it will use the default port for themode 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 byrequestStarted() andrequestFinished().
When the request is started therequestStarted() signal is emitted. When it is finished therequestFinished() signal is emitted.
See alsoget(),post(),head(),request(),requestStarted(),requestFinished(), anddone().
Enables HTTP proxy support, using the proxy serverhost on portport.username andpassword can be provided if the proxy server requires authentication.
Example:
void Ticker::getTicks(){ http=newQHttp(this); connect(http, SIGNAL(done(bool)),this, SLOT(showPage())); http->setProxy("proxy.example.com",3128); http->setHost("ticker.example.com"); http->get("/ticks.asp");}void Ticker::showPage(){ display(http->readAll());}
QHttp supports non-transparent web proxy servers only, such as the Squid Web proxy cache server (fromhttp://www.squid.org/). For transparent proxying, such as SOCKS5, useQNetworkProxy instead.
Note:setProxy() has to be called beforesetHost() for it to take effect. If setProxy() is called aftersetHost(), then it will not apply until aftersetHost() is called again.
See alsoQFtp::setProxy().
This is an overloaded function.
Enables HTTP proxy support using the proxy settings fromproxy. Ifproxy is a transparent proxy,QHttp will callQAbstractSocket::setProxy() on the underlying socket. If the type isQNetworkProxy::HttpCachingProxy,QHttp will behave like the previous function.
Note:for compatibility with Qt 4.3, if the proxy type isQNetworkProxy::HttpProxy and the request type is unencrypted (that is,ConnectionModeHttp),QHttp will treat the proxy as a caching proxy.
Replaces the internalQTcpSocket thatQHttp uses withsocket. This is useful if you want to use your own customQTcpSocket subclass instead of the plainQTcpSocket thatQHttp uses by default.QHttp does not take ownership of the socket, and will not deletesocket 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 byrequestStarted() andrequestFinished().
When the request is started therequestStarted() signal is emitted. When it is finished therequestFinished() signal is emitted.
Note: IfQHttp is used in a non-GUI thread that runs its own event loop, you must movesocket to that thread before calling setSocket().
See alsoQObject::moveToThread() andThread Support in Qt.
This function sets the user nameuserName and passwordpassword 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 byrequestStarted() andrequestFinished().
When the request is started therequestStarted() signal is emitted. When it is finished therequestFinished() signal is emitted.
[signal]void QHttp::sslErrors(constQList<QSslError> & errors)Forwards the sslErrors signal from theQSslSocket used inQHttp.errors is the list of errors that occurred during the SSL handshake. Unless you callignoreSslErrors() from within a slot connected to this signal when an error occurs,QHttp will tear down the connection immediately after emitting the signal.
This function was introduced in Qt 4.3.
See alsoQSslSocket andQSslSocket::ignoreSslErrors().
Returns the current state of the object. When the state changes, thestateChanged() signal is emitted.
See alsoState andstateChanged().
[signal]void QHttp::stateChanged(int state)This signal is emitted when the state of theQHttp object changes. The argumentstate is the new state of the connection; it is one of theState values.
This usually happens when a request is started, but it can also happen when the server closes the connection or when a call toclose() succeeded.
See alsoget(),post(),head(),request(),close(),state(), andState.
© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.