⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 qhttp.cpp

📁 奇趣公司比较新的qt/emd版本
💻 CPP
📖 第 1 页 / 共 5 页
字号:
    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 Trolltech home page (i.e. the URL    \c http://www.trolltech.com/index.html):    \code    QHttpRequestHeader header("GET", "/index.html");    header.setValue("Host", "www.trolltech.com");    http->setHost("www.trolltech.com");    http->request(header);    \endcode    For the common HTTP requests \c GET, \c POST and \c 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:    \code    http->setHost("www.trolltech.com"); // id == 1    http->get("/index.html");           // id == 2    \endcode    For this example the following sequence of signals is emitted    (with small variations, depending on network traffic, etc.):    \code    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)    \endcode    The dataSendProgress() and dataReadProgress() signals in the above    example are useful if you want to show a \link QProgressBar    progress bar\endlink 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    \code    http->setHost("www.foo.bar");       // id == 1    http->get("/index.html");           // id == 2    http->post("register.html", data);  // id == 3    \endcode    and the get() request fails because the host lookup fails, then    the post() request is never executed and the signals would look    like this:    \code    requestStarted(1)    requestFinished(1, false)    requestStarted(2)    stateChanged(HostLookup)    requestFinished(2, true)    done(true)    stateChanged(Unconnected)    \endcode    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 \link    QHttpResponseHeader::statusCode() status code \endlink 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.    \sa QFtp, {HTTP Example}, {Torrent Example}*//*!    Constructs a QHttp object. The \a parent parameter is passed on    to the QObject constructor.*/QHttp::QHttp(QObject *parent)    : QObject(*new QHttpPrivate, parent){    Q_D(QHttp);    d->init();}/*!    Constructs a QHttp object. Subsequent requests are done by    connecting to the server \a hostName on port \a port.    The \a parent parameter is passed on to the QObject constructor.    \sa setHost()*/QHttp::QHttp(const QString &hostName, quint16 port, QObject *parent)    : QObject(*new QHttpPrivate, parent){    Q_D(QHttp);    d->init();    d->hostName = hostName;    d->port = port;}/*!    Constructs a QHttp object. Subsequent requests are done by    connecting to the server \a hostName on port \a port using the    connection mode \a mode.    If port is 0, it will use the default port for the \a mode used    (80 for Http and 443 for Https).    The \a parent parameter is passed on to the QObject constructor.    \sa setHost()*/QHttp::QHttp(const QString &hostName, ConnectionMode mode, quint16 port, QObject *parent)    : QObject(*new QHttpPrivate, parent){    Q_D(QHttp);    d->init();    d->hostName = hostName;    if (port == 0)         port = (mode == ConnectionModeHttp) ? 80 : 443;            d->port = port;    d->mode = mode;}void QHttpPrivate::init(){    Q_Q(QHttp);    errorString = QLatin1String(QT_TRANSLATE_NOOP("QHttp", "Unknown error"));    QMetaObject::invokeMethod(q, "_q_slotDoFinished", Qt::QueuedConnection);}/*!    Destroys the QHttp object. If there is an open connection, it is    closed.*/QHttp::~QHttp(){    abort();}/*!    \enum QHttp::ConnectionMode    \since 4.3    This enum is used to specify the mode of connection to use:    \value ConnectionModeHttp The connection is a regular Http connection to the server    \value 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.    \sa QSslSocket*//*!    \enum QHttp::State    This enum is used to specify the state the client is in:    \value Unconnected There is no connection to the host.    \value HostLookup A host name lookup is in progress.    \value Connecting An attempt to connect to the host is in progress.    \value Sending The client is sending its request to the server.    \value Reading The client's request has been sent and the client    is reading the server's response.    \value Connected The connection to the host is open, but the client is    neither sending a request, nor waiting for a response.    \value Closing The connection is closing down, but is not yet    closed. (The state will be \c Unconnected when the connection is    closed.)    \sa stateChanged() state()*//*!  \enum QHttp::Error    This enum identifies the error that occurred.    \value NoError No error occurred.    \value HostNotFound The host name lookup failed.    \value ConnectionRefused The server refused the connection.    \value UnexpectedClose The server closed the connection unexpectedly.    \value InvalidResponseHeader The server sent an invalid response header.    \value WrongContentLength The client could not read the content correctly    because an error with respect to the content length occurred.    \value Aborted The request was aborted with abort().    \value ProxyAuthenticationRequiredError QHttp is using a proxy, and the    proxy server requires authentication to establish a connection.    \value AuthenticationRequiredError The web server requires authentication    to complete the request.    \value UnknownError An error other than those specified above    occurred.    \sa error()*//*!    \fn void QHttp::stateChanged(int state)    This signal is emitted when the state of the QHttp object changes.    The argument \a state is the new state of the connection; it is    one of the \l State values.    This usually happens when a request is started, but it can also    happen when the server closes the connection or when a call to    close() succeeded.    \sa get() post() head() request() close() state() State*//*!    \fn void QHttp::responseHeaderReceived(const QHttpResponseHeader &resp);    This signal is emitted when the HTTP header of a server response    is available. The header is passed in \a resp.    \sa get() post() head() request() readyRead()*//*!    \fn void QHttp::readyRead(const QHttpResponseHeader &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 is \e not emitted; instead the data    is written directly to the device.    The response header is passed in \a 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.    \sa get() post() request() readAll() read() bytesAvailable()*//*!    \fn 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.    \a done is the amount of data that has already arrived and \a    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 \a total is 0.(If you connect to a QProgressBar, the    progress bar shows a busy indicator if the total is 0).    \warning \a done and \a total are not necessarily the size in    bytes, since for large files these values might need to be    "scaled" to avoid overflow.    \sa dataReadProgress(), post(), request(), QProgressBar*//*!    \fn 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.    \a done is the amount of data that has already arrived and \a    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 \a total is 0.(If you connect to a QProgressBar, the    progress bar shows a busy indicator if the total is 0).    \warning \a done and \a total are not necessarily the size in    bytes, since for large files these values might need to be    "scaled" to avoid overflow.    \sa dataSendProgress() get() post() request() QProgressBar*//*!    \fn void QHttp::requestStarted(int id)    This signal is emitted when processing the request identified by    \a id starts.    \sa requestFinished() done()*//*!    \fn void QHttp::requestFinished(int id, bool error)    This signal is emitted when processing the request identified by    \a id has finished. \a error is true if an error occurred during    the processing; otherwise \a error is false.    \sa requestStarted() done() error() errorString()*//*!    \fn void QHttp::done(bool error)    This signal is emitted when the last pending request has finished;    (it is emitted after the last request's requestFinished() signal).    \a error is true if an error occurred during the processing;    otherwise \a error is false.    \sa requestFinished() error() errorString()*/#ifndef QT_NO_NETWORKPROXY/*!    \fn void QHttp::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)    \since 4.3    This signal can be emitted when a \a proxy that requires    authentication is used. The \a authenticator 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.    \sa QAuthenticator, QNetworkProxy*/#endif/*!    \fn void QHttp::authenticationRequired(const QString &hostname, quint16 port, QAuthenticator *authenticator)    \since 4.3    This signal can be emitted when a web server on a given \a hostname and \a    port requires authentication. The \a authenticator 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.    \sa QAuthenticator, QNetworkProxy*//*!    \fn void QHttp::sslErrors(const QList<QSslError> &errors)    \since 4.3    Forwards the sslErrors signal from the QSslSocket used in QHttp. \a 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.    \sa QSslSocket QSslSocket::ignoreSslErrors()*//*!    Aborts the current request and deletes all scheduled requests.    For the current request, the requestFinished() signal with the \c    error argument \c 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 \c error    argument \c true).    \sa clearPendingRequests()*/void QHttp::abort(){    Q_D(QHttp);    if (d->pending.isEmpty())        return;    d->finishedWithError(tr("Request aborted"), Aborted);    clearPendingRequests();    if (d->socket)        d->socket->abort();    d->closeConn();}/*!    Returns the number of bytes that can be read from the response    content at the moment.    \sa get() post() request() readyRead() read() readAll()*/qint64 QHttp::bytesAvailable() const{    Q_D(const QHttp);#if defined(QHTTP_DEBUG)    qDebug("QHttp::bytesAvailable(): %d bytes", (int)d->rba.size());#endif    return qint64(d->rba.size());}/*! \fn qint64 QHttp::readBlock(char *data, quint64 maxlen)    Use read() instead.*//*!    Reads \a maxlen bytes from the response content into \a data and    returns the number of bytes read. Returns -1 if an error occurred.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -