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

📄 q3http.cpp

📁 奇趣公司比较新的qt/emd版本
💻 CPP
📖 第 1 页 / 共 5 页
字号:
/*!    Returns the minor protocol-version of the HTTP request header.    \sa majorVersion() method() path() setRequest()*/int Q3HttpRequestHeader::minorVersion() const{    return minVer;}/*! \reimp*/bool Q3HttpRequestHeader::parseLine( const QString& line, int number ){    if ( number != 0 )	return Q3HttpHeader::parseLine( line, number );    QStringList lst = QStringList::split( QLatin1String(" "), line.simplifyWhiteSpace() );    if ( lst.count() > 0 ) {	m = lst[0];	if ( lst.count() > 1 ) {	    p = lst[1];	    if ( lst.count() > 2 ) {		QString v = lst[2];		if ( v.length() >= 8 && v.left( 5 ) == QLatin1String("HTTP/") &&			v[5].isDigit() && v[6] == QLatin1Char('.') && v[7].isDigit() ) {		    majVer = v[5].latin1() - '0';		    minVer = v[7].latin1() - '0';		    return true;		}	    }	}    }    return false;}/*! \reimp*/QString Q3HttpRequestHeader::toString() const{    QString first( QLatin1String("%1 %2"));    QString last(QLatin1String(" HTTP/%3.%4\r\n%5\r\n") );    return first.arg( m ).arg( p ) +	last.arg( majVer ).arg( minVer ).arg( Q3HttpHeader::toString());}/**************************************************** * * Q3Http * ****************************************************//*!    \class Q3Http q3http.h    \brief The Q3Http class provides an implementation of the HTTP protocol.    \compat    This class provides two different interfaces: one is the    Q3NetworkProtocol interface that allows you to use HTTP through the    QUrlOperator abstraction. The other is a direct interface to HTTP    that allows you to have more control over the requests and that    allows you to access the response header fields.    Don't mix the two interfaces, since the behavior is not    well-defined.    If you want to use Q3Http with the Q3NetworkProtocol interface, you    do not use it directly, but rather through a QUrlOperator, for    example:    \code    QUrlOperator op( "http://www.trolltech.com" );    op.get( "index.html" );    \endcode    This code will only work if the Q3Http class is registered; to    register the class, you must call q3InitNetworkProtocols() before    using a QUrlOperator with HTTP.    The Q3NetworkProtocol interface for HTTP only supports the    operations operationGet() and operationPut(), i.e.    QUrlOperator::get() and QUrlOperator::put(), if you use it with a    QUrlOperator.    The rest of this descrption describes the direct interface to    HTTP.    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 Trolltech home page (i.e. the URL    http://www.trolltech.com/index.html):    \code    Q3HttpRequestHeader 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, Q3Http    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 readBlock()    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 reqeusts    \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 behaviour, 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    Q3HttpResponseHeader::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 Q3NetworkProtocol, Q3UrlOperator, Q3Ftp*//*!    Constructs a Q3Http object.*/Q3Http::Q3Http(){    init();}/*!    Constructs a Q3Http object. The parameters \a parent and \a name    are passed on to the QObject constructor.*/Q3Http::Q3Http( QObject* parent, const char* name ){    if ( parent )	parent->insertChild( this );    setName( name );    init();}/*!    Constructs a Q3Http object. Subsequent requests are done by    connecting to the server \a hostname on port \a port. The    parameters \a parent and \a name are passed on to the QObject    constructor.    \sa setHost()*/Q3Http::Q3Http( const QString &hostname, Q_UINT16 port, QObject* parent, const char* name ){    if ( parent )	parent->insertChild( this );    setName( name );    init();    d->hostname = hostname;    d->port = port;}void Q3Http::init(){    bytesRead = 0;    d = new Q3HttpPrivate;    d->errorString = QHttp::tr( "Unknown error" );    connect( &d->socket, SIGNAL(connected()),	    this, SLOT(slotConnected()) );    connect( &d->socket, SIGNAL(connectionClosed()),	    this, SLOT(slotClosed()) );    connect( &d->socket, SIGNAL(delayedCloseFinished()),	    this, SLOT(slotClosed()) );    connect( &d->socket, SIGNAL(readyRead()),	    this, SLOT(slotReadyRead()) );    connect( &d->socket, SIGNAL(error(int)),	    this, SLOT(slotError(int)) );    connect( &d->socket, SIGNAL(bytesWritten(int)),	    this, SLOT(slotBytesWritten(int)) );    d->idleTimer = startTimer( 0 );}/*!    Destroys the Q3Http object. If there is an open connection, it is    closed.*/Q3Http::~Q3Http(){    abort();    delete d;}/*!    \enum Q3Http::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 Q3Http::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 UnknownError An error other than those specified above    occurred.    \sa error()*//*!    \fn void Q3Http::stateChanged( int state )    This signal is emitted when the state of the Q3Http 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    closeConnection() succeeded.    \sa get() post() head() request() closeConnection() state() State*//*!    \fn void Q3Http::responseHeaderReceived( const Q3HttpResponseHeader& 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 Q3Http::readyRead( const Q3HttpResponseHeader& 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 readBlock() 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() readBlock() bytesAvailable()*//*!    \fn void Q3Http::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::setValue()*//*!    \fn void Q3Http::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::setValue()*//*!    \fn void Q3Http::requestStarted( int id )    This signal is emitted when processing the request identified by    \a id starts.    \sa requestFinished() done()*//*!    \fn void Q3Http::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 Q3Http::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()*//*!    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 Q3Http::abort(){    Q3HttpRequest *r = d->pending.getFirst();    if ( r == 0 )	return;    finishedWithError( QHttp::tr("Request aborted"), Aborted );    clearPendingRequests();    d->socket.clearPendingData();    close();}/*!    Returns the number of bytes that can be read from the response    content at the moment.    \sa get() post() request() readyRead() readBlock() readAll()*/

⌨️ 快捷键说明

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