Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Q3Http Class Reference

The Q3Http class provides an implementation of the HTTP protocol. More...

 #include <Q3Http>

This class is part of the Qt 3 support library. It is provided to keep old source code working. We strongly advise against using it in new code. See Porting to Qt 4 for more information.

Inherits: Q3NetworkProtocol.

Public Types

enum Error { NoError, HostNotFound, ConnectionRefused, UnexpectedClose, ..., UnknownError }
enum State { Unconnected, HostLookup, Connecting, Sending, ..., Closing }

Public Functions

Q3Http ()
Q3Http ( QObject * parent, const char * name = 0 )
Q3Http ( const QString & hostname, Q_UINT16 port = 80, QObject * parent = 0, const char * name = 0 )
virtual ~Q3Http ()
Q_ULONG bytesAvailable () const
void clearPendingRequests ()
int closeConnection ()
QIODevice * currentDestinationDevice () const
int currentId () const
Q3HttpRequestHeader 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 )
int post ( const QString & path, QIODevice * data, QIODevice * to = 0 )
int post ( const QString & path, const QByteArray & data, QIODevice * to = 0 )
QByteArray readAll ()
Q_LONG readBlock ( char * data, Q_ULONG maxlen )
int request ( const Q3HttpRequestHeader & header, QIODevice * data = 0, QIODevice * to = 0 )
int request ( const Q3HttpRequestHeader & header, const QByteArray & data, QIODevice * to = 0 )
int setHost ( const QString & hostname, Q_UINT16 port = 80 )
State state () const

Reimplemented Public Functions

virtual int supportedOperations () const

Public Slots

void abort ()
  • 1 public slot inherited from QObject

Signals

void dataReadProgress ( int done, int total )
void dataSendProgress ( int done, int total )
void done ( bool error )
void readyRead ( const Q3HttpResponseHeader & resp )
void requestFinished ( int id, bool error )
void requestStarted ( int id )
void responseHeaderReceived ( const Q3HttpResponseHeader & resp )
void stateChanged ( int state )

Reimplemented Protected Functions

virtual void operationGet ( Q3NetworkOperation * op )
virtual void operationPut ( Q3NetworkOperation * op )
virtual void timerEvent ( QTimerEvent * e )

Additional Inherited Members

Detailed Description

The Q3Http class provides an implementation of the HTTP protocol.

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:

 QUrlOperator op( "http://qt.nokia.com" );
 op.get( "index.html" );

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 Qt website (i.e. the URL http://qt.nokia.com/index.html):

 Q3HttpRequestHeader header( "GET", "/index.html" );
 header.setValue( "Host", "qt.nokia.com" );
 http->setHost( "qt.nokia.com" );
 http->request( header );

For the common HTTP requests GET, POST and 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:

 http->setHost( "qt.nokia.com" ); // id == 1
 http->get( "/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 )

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 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

 http->setHost( "www.foo.bar" );       // id == 1
 http->get( "/index.html" );           // id == 2
 http->post( "register.html", data );  // id == 3

and the get() request fails because the host lookup fails, then the post() 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 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 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.

See also Q3NetworkProtocol, Q3UrlOperator, and Q3Ftp.

Member Type Documentation

enum Q3Http::Error

This enum identifies the error that occurred.

ConstantValueDescription
Q3Http::NoError0No error occurred.
Q3Http::HostNotFound2The host name lookup failed.
Q3Http::ConnectionRefused3The server refused the connection.
Q3Http::UnexpectedClose4The server closed the connection unexpectedly.
Q3Http::InvalidResponseHeader5The server sent an invalid response header.
Q3Http::WrongContentLength6The client could not read the content correctly because an error with respect to the content length occurred.
Q3Http::Aborted7The request was aborted with abort().
Q3Http::UnknownError1An error other than those specified above occurred.

See also error().

enum Q3Http::State

This enum is used to specify the state the client is in:

ConstantValueDescription
Q3Http::Unconnected0There is no connection to the host.
Q3Http::HostLookup1A host name lookup is in progress.
Q3Http::Connecting2An attempt to connect to the host is in progress.
Q3Http::Sending3The client is sending its request to the server.
Q3Http::Reading4The client's request has been sent and the client is reading the server's response.
Q3Http::Connected5The connection to the host is open, but the client is neither sending a request, nor waiting for a response.
Q3Http::Closing6The connection is closing down, but is not yet closed. (The state will be Unconnected when the connection is closed.)

See also stateChanged() and state().

Member Function Documentation

Q3Http::Q3Http ()

Constructs a Q3Http object.

Q3Http::Q3Http ( QObject * parent, const char * name = 0 )

Constructs a Q3Http object. The parameters parent and name are passed on to the QObject constructor.

Q3Http::Q3Http ( const QString & hostname, Q_UINT16 port = 80, QObject * parent = 0, const char * name = 0 )

Constructs a Q3Http object. Subsequent requests are done by connecting to the server hostname on port port. The parameters parent and name are passed on to the QObject constructor.

See also setHost().

Q3Http::~Q3Http () [virtual]

Destroys the Q3Http object. If there is an open connection, it is closed.

void Q3Http::abort () [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).

See also clearPendingRequests().

Q_ULONG Q3Http::bytesAvailable () const

Returns the number of bytes that can be read from the response content at the moment.

See also get(), post(), request(), readyRead(), readBlock(), and readAll().

void Q3Http::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().

See also hasPendingRequests() and abort().

int Q3Http::closeConnection ()

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(), Q3Http sets the connection to be keep-alive. You can also do this using the header you pass to the request() function. Q3Http only closes the connection to the HTTP server if the response header requires it to do so.

The function does not block and 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.

See also stateChanged(), abort(), requestStarted(), requestFinished(), and done().

QIODevice * Q3Http::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.

See also get(), post(), and request().

int Q3Http::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).

See also currentRequest().

Q3HttpRequestHeader Q3Http::currentRequest () const

Returns the request header of the HTTP request being executed. If the request is one issued by setHost() or closeConnection(), it returns an invalid request header, i.e. Q3HttpRequestHeader::isValid() returns false.

See also currentId().

QIODevice * Q3Http::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.

See also currentDestinationDevice(), post(), and request().

void Q3Http::dataReadProgress ( int done, int total ) [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).

Warning: done and total are not necessarily the size in bytes, since for large files these values might need to be "scaled" to avoid overflow.

See also dataSendProgress(), get(), post(), request(), and QProgressBar::setValue().

void Q3Http::dataSendProgress ( int done, int total ) [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).

Warning: done and total are not necessarily the size in bytes, since for large files these values might need to be "scaled" to avoid overflow.

See also dataReadProgress(), post(), request(), and QProgressBar::setValue().

void Q3Http::done ( bool error ) [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.

See also requestFinished(), error(), and errorString().

Error Q3Http::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.

QString Q3Http::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.

int Q3Http::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 an absolute path like /index.html or an absolute URI like http://example.com/index.html.

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 and 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.

See also setHost(), post(), head(), request(), requestStarted(), requestFinished(), and done().

bool Q3Http::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.

See also clearPendingRequests(), currentId(), and currentRequest().

int Q3Http::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 and 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.

See also setHost(), get(), post(), request(), requestStarted(), requestFinished(), and done().

void Q3Http::operationGet ( Q3NetworkOperation * op ) [virtual protected]

Reimplemented from Q3NetworkProtocol::operationGet().

void Q3Http::operationPut ( Q3NetworkOperation * op ) [virtual protected]

Reimplemented from Q3NetworkProtocol::operationPut().

int Q3Http::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.

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 and 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.

See also setHost(), get(), head(), request(), requestStarted(), requestFinished(), and done().

int Q3Http::post ( const QString & path, const QByteArray & data, QIODevice * to = 0 )

This is an overloaded function.

data is used as the content data of the HTTP request.

QByteArray Q3Http::readAll ()

Reads all the bytes from the response content and returns them.

See also get(), post(), request(), readyRead(), bytesAvailable(), and readBlock().

Q_LONG Q3Http::readBlock ( char * data, Q_ULONG maxlen )

Reads maxlen bytes from the response content into data and returns the number of bytes read. Returns -1 if an error occurred.

See also get(), post(), request(), readyRead(), bytesAvailable(), and readAll().

void Q3Http::readyRead ( const Q3HttpResponseHeader & resp ) [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 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.

See also get(), post(), request(), readAll(), readBlock(), and bytesAvailable().

int Q3Http::request ( const Q3HttpRequestHeader & 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 and 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.

See also setHost(), get(), post(), head(), requestStarted(), requestFinished(), and done().

int Q3Http::request ( const Q3HttpRequestHeader & header, const QByteArray & data, QIODevice * to = 0 )

This is an overloaded function.

data is used as the content data of the HTTP request.

void Q3Http::requestFinished ( int id, bool error ) [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.

See also requestStarted(), done(), error(), and errorString().

void Q3Http::requestStarted ( int id ) [signal]

This signal is emitted when processing the request identified by id starts.

See also requestFinished() and done().

void Q3Http::responseHeaderReceived ( const Q3HttpResponseHeader & resp ) [signal]

This signal is emitted when the HTTP header of a server response is available. The header is passed in resp.

See also get(), post(), head(), request(), and readyRead().

int Q3Http::setHost ( const QString & hostname, Q_UINT16 port = 80 )

Sets the HTTP server that is used for requests to hostname on port port.

The function does not block and 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.

See also get(), post(), head(), request(), requestStarted(), requestFinished(), and done().

State Q3Http::state () const

Returns the current state of the object. When the state changes, the stateChanged() signal is emitted.

See also State and stateChanged().

void Q3Http::stateChanged ( int state ) [signal]

This signal is emitted when the state of the Q3Http object changes. The argument state is the new state of the connection; it is one of the 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.

See also get(), post(), head(), request(), closeConnection(), state(), and State.

int Q3Http::supportedOperations () const [virtual]

Reimplemented from Q3NetworkProtocol::supportedOperations().

void Q3Http::timerEvent ( QTimerEvent * e ) [virtual protected]

Reimplemented from QObject::timerEvent().

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 64
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. La rubrique Qt a besoin de vous ! 1
Page suivante

Le Qt Quarterly au hasard

Logo

Un widget de correspondance de données avec Qt

Qt Quarterly est la revue trimestrielle proposée par Nokia et à destination des développeurs Qt. Ces articles d'une grande qualité technique sont rédigés par des experts Qt. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 4.7-snapshot
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web