Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

Q3Http Class

TheQ3Http class provides an implementation of the HTTP protocol.More...

Header:#include <Q3Http>
Inherits:Q3NetworkProtocol

Public Types

enumError { NoError, HostNotFound, ConnectionRefused, UnexpectedClose, ..., UnknownError }
enumState { 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_ULONGbytesAvailable() const
voidclearPendingRequests()
intcloseConnection()
QIODevice *currentDestinationDevice() const
intcurrentId() const
Q3HttpRequestHeadercurrentRequest() const
QIODevice *currentSourceDevice() const
Errorerror() const
QStringerrorString() const
intget(const QString & path, QIODevice * to = 0)
boolhasPendingRequests() const
inthead(const QString & path)
intpost(const QString & path, QIODevice * data, QIODevice * to = 0)
intpost(const QString & path, const QByteArray & data, QIODevice * to = 0)
QByteArrayreadAll()
Q_LONGreadBlock(char * data, Q_ULONG maxlen)
intrequest(const Q3HttpRequestHeader & header, QIODevice * data = 0, QIODevice * to = 0)
intrequest(const Q3HttpRequestHeader & header, const QByteArray & data, QIODevice * to = 0)
intsetHost(const QString & hostname, Q_UINT16 port = 80)
Statestate() const

Reimplemented Public Functions

virtual intsupportedOperations() const

Public Slots

voidabort()
  • 1 public slot inherited fromQObject

Signals

voiddataReadProgress(int done, int total)
voiddataSendProgress(int done, int total)
voiddone(bool error)
voidreadyRead(const Q3HttpResponseHeader & resp)
voidrequestFinished(int id, bool error)
voidrequestStarted(int id)
voidresponseHeaderReceived(const Q3HttpResponseHeader & resp)
voidstateChanged(int state)

Reimplemented Protected Functions

virtual voidoperationGet(Q3NetworkOperation * op)
virtual voidoperationPut(Q3NetworkOperation * op)
virtual voidtimerEvent(QTimerEvent * e)

Additional Inherited Members

Detailed Description

TheQ3Http class provides an implementation of the HTTP protocol.

This class provides two different interfaces: one is theQ3NetworkProtocol interface that allows you to use HTTP through theQUrlOperator 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 useQ3Http with theQ3NetworkProtocol interface, you do not use it directly, but rather through aQUrlOperator, for example:

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

This code will only work if theQ3Http class is registered; to register the class, you must callq3InitNetworkProtocols() before using aQUrlOperator with HTTP.

TheQ3NetworkProtocol interface for HTTP only supports the operationsoperationGet() andoperationPut(), i.e. QUrlOperator::get() and QUrlOperator::put(), if you use it with aQUrlOperator.

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() 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):

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

For the common HTTP requestsGET,POST andHEAD,Q3Http 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("/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 thereadBlock() 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 reqeusts

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 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 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 alsoQ3NetworkProtocol, Q3UrlOperator, andQ3Ftp.

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 withabort().
Q3Http::UnknownError1An error other than those specified above occurred.

See alsoerror().

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 beUnconnected when the connection is closed.)

See alsostateChanged() andstate().

Member Function Documentation

Q3Http::Q3Http()

Constructs aQ3Http object.

Q3Http::Q3Http(QObject * parent, constchar * name = 0)

Constructs aQ3Http object. The parametersparent andname are passed on to theQObject constructor.

Q3Http::Q3Http(constQString & hostname,Q_UINT16 port = 80,QObject * parent = 0, constchar * name = 0)

Constructs aQ3Http object. Subsequent requests are done by connecting to the serverhostname on portport. The parametersparent andname are passed on to theQObject constructor.

See alsosetHost().

[virtual]Q3Http::~Q3Http()

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

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

Q_ULONG Q3Http::bytesAvailable() const

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

See alsoget(),post(),request(),readyRead(),readBlock(), andreadAll().

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, useabort().

See alsohasPendingRequests() andabort().

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 withget(),post() andhead(),Q3Http sets the connection to be keep-alive. You can also do this using the header you pass to therequest() 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 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().

QIODevice * Q3Http::currentDestinationDevice() const

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 alsoget(),post(), andrequest().

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 alsocurrentRequest().

Q3HttpRequestHeader Q3Http::currentRequest() const

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

See alsocurrentId().

QIODevice * Q3Http::currentSourceDevice() const

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

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

[signal]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.

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

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

Error Q3Http::error() const

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.

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 arequestFinished() or adone() signal with theerror argumenttrue.

int Q3Http::get(constQString & path,QIODevice * to = 0)

Sends a get 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.

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

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 isnot considered as a scheduled request.

See alsoclearPendingRequests(),currentId(), andcurrentRequest().

int Q3Http::head(constQString & path)

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

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

Reimplemented fromQ3NetworkProtocol::operationGet().

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

Reimplemented fromQ3NetworkProtocol::operationPut().

int Q3Http::post(constQString & path,QIODevice * data,QIODevice * to = 0)

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.

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

int Q3Http::post(constQString & path, constQByteArray & 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 alsoget(),post(),request(),readyRead(),bytesAvailable(), andreadBlock().

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

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().

[signal]void Q3Http::readyRead(constQ3HttpResponseHeader & 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() orreadBlock() 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(),readBlock(), andbytesAvailable().

int Q3Http::request(constQ3HttpRequestHeader & header,QIODevice * data = 0,QIODevice * to = 0)

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

int Q3Http::request(constQ3HttpRequestHeader & header, constQByteArray & data,QIODevice * to = 0)

This is an overloaded function.

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

[signal]void Q3Http::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 Q3Http::requestStarted(int id)

This signal is emitted when processing the request identified byid starts.

See alsorequestFinished() anddone().

[signal]void Q3Http::responseHeaderReceived(constQ3HttpResponseHeader & 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().

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

Sets the HTTP server that is used for requests tohostname on portport.

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 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().

State Q3Http::state() const

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

See alsoState andstateChanged().

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

This signal is emitted when the state of theQ3Http 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 tocloseConnection() succeeded.

See alsoget(),post(),head(),request(),closeConnection(),state(), andState.

[virtual]int Q3Http::supportedOperations() const

Reimplemented fromQ3NetworkProtocol::supportedOperations().

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

Reimplemented fromQObject::timerEvent().

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


[8]ページ先頭

©2009-2025 Movatter.jp