Nuria Framework - Network
Network module of the NuriaProject Framework
 All Classes Functions Typedefs Enumerations Enumerator
Public Types | Public Slots | Signals | Public Member Functions | Static Public Member Functions | Protected Member Functions | Friends | List of all members
Nuria::HttpClient Class Reference

The HttpClient class represents a connection to a client. More...

#include <httpclient.hpp>

Inheritance diagram for Nuria::HttpClient:

Public Types

enum  HttpVersion { HttpUnknown, Http1_0, Http1_1 }
 
enum  HttpVerb {
  InvalidVerb = 0, GET = 1, POST = 2, HEAD = 4,
  PUT = 8, DELETE = 16, AllVerbs = GET | POST | HEAD | PUT | DELETE
}
 
enum  HttpHeader {
  HeaderCacheControl = 0, HeaderContentLength, HeaderContentType, HeaderConnection,
  HeaderDate, HeaderHost = 1000, HeaderUserAgent, HeaderAccept,
  HeaderAcceptCharset, HeaderAcceptEncoding, HeaderAcceptLanguage, HeaderAuthorization,
  HeaderCookie, HeaderRange, HeaderReferer, HeaderDoNotTrack,
  HeaderExpect, HeaderContentEncoding = 2000, HeaderContentLanguage, HeaderContentDisposition,
  HeaderContentRange, HeaderLastModified, HeaderRefresh, HeaderSetCookie,
  HeaderTransferEncoding, HeaderLocation
}
 
typedef QMultiMap< QByteArray,
QByteArray > 
HeaderMap
 
typedef QMap< QByteArray,
QNetworkCookie > 
Cookies
 

Public Slots

bool killConnection (int error, const QString &cause=QString())
 
bool sendResponseHeader ()
 
void close () override
 
void forceClose ()
 

Signals

void disconnected ()
 
void headerReady ()
 
void postBodyComplete ()
 

Public Member Functions

 HttpClient (HttpTransport *transport, HttpServer *server)
 
virtual ~HttpClient ()
 
HttpTransporttransport () const
 
bool isHeaderReady () const
 
bool responseHeaderSent () const
 
HttpVerb verb () const
 
QUrl path () const
 
bool hasRequestHeader (const QByteArray &key) const
 
bool hasRequestHeader (HttpHeader header) const
 
QByteArray requestHeader (const QByteArray &key) const
 
QByteArray requestHeader (HttpHeader header) const
 
QList< QByteArray > requestHeaders (const QByteArray &key) const
 
QList< QByteArray > requestHeaders (HttpHeader header) const
 
const HeaderMaprequestHeaders () const
 
bool hasResponseHeader (const QByteArray &key) const
 
bool hasResponseHeader (HttpHeader header) const
 
const HeaderMapresponseHeaders () const
 
QList< QByteArray > responseHeaders (const QByteArray &key) const
 
QList< QByteArray > responseHeaders (HttpHeader header) const
 
bool setResponseHeader (const QByteArray &key, const QByteArray &value, bool append=false)
 
bool setResponseHeader (HttpHeader header, const QByteArray &value, bool append=false)
 
bool setResponseHeaders (const HeaderMap &headers)
 
bool pipeToClient (QIODevice *device, qint64 maxlen=-1)
 
bool pipeFromPostBody (QIODevice *device, bool takeOwnership=false)
 
qint64 rangeStart () const
 
qint64 rangeEnd () const
 
qint64 contentLength () const
 
bool setRangeStart (qint64 pos)
 
bool setRangeEnd (qint64 pos)
 
bool setContentLength (qint64 length)
 
virtual bool isSequential () const
 
qint64 postBodyLength () const
 
qint64 postBodyTransferred ()
 
QHostAddress localAddress () const
 
quint16 localPort () const
 
QHostAddress peerAddress () const
 
quint16 peerPort () const
 
int responseCode () const
 
void setResponseCode (int code)
 
bool isConnectionSecure () const
 
HttpServerhttpServer () const
 
Cookies cookies ()
 
QNetworkCookie cookie (const QByteArray &name)
 
bool hasCookie (const QByteArray &name)
 
void setCookie (const QByteArray &name, const QByteArray &value, const QDateTime &expires, bool secure=false)
 
void setCookie (const QByteArray &name, const QByteArray &value, qint64 maxAge=0, bool secure=false)
 
void setCookie (const QNetworkCookie &cookie)
 
void removeCookie (const QByteArray &name)
 
bool keepConnectionOpen () const
 
void setKeepConnectionOpen (bool keepOpen)
 
SlotInfo slotInfo () const
 
void setSlotInfo (const SlotInfo &info)
 
bool hasReadablePostBody () const
 
HttpPostBodyReaderpostBodyReader ()
 
bool atEnd () const override
 
qint64 pos () const override
 
qint64 size () const override
 
bool seek (qint64 pos) override
 
bool reset () override
 

Static Public Member Functions

static QByteArray httpStatusCodeName (int code)
 
static QByteArray httpHeaderName (HttpHeader header)
 

Protected Member Functions

virtual qint64 readData (char *data, qint64 maxlen)
 
virtual qint64 writeData (const char *data, qint64 len)
 
bool resolveUrl (const QUrl &url)
 
bool bufferPostBody ()
 

Friends

class HttpServer
 
class HttpNode
 

Detailed Description

The HttpClient class represents a connection to a client.

This class is used whenever interaction with the HTTP client is necessary. It provides a simple way to transfer data from and to the client.

Note
As of now, HttpClient doesn't support Connection: keep-alive. This means that a client has to open a connection for each request. This problem will be addressed in the future.
Sending and receiving data
HttpClient is a subclass of QIODevice. Slots that expect a POST body can read it by using readAll or similar QIODevice methods. To send data to the client simply use write or similar. There is really not much to say about this - You can do anything with it that you can do with any QIODevice subclass.
Note
HttpClient is a random-access device. Methods such as read(), pos() and seek() always refer to the POST body. Writing always refers to sending data back to the client.
Piping
Additionally to the generic read and write methods, you can also pipe other QIODevice*'s to the client. This means that the implementation will take care of data transfer and will close the connection automatically on completion. This is useful when you want to send a large chunk of data. Another use-case is to combine this with QProcess when you want or need to interact with other applications.

This is possible for both directions: You can either pipe a buffer to the client, or pipe the clients post body into a QIODevice.

An example would be to use this to process a file while the user is still uploading it.

Note
Don't forget to enable streaming mode in the SlotInfo of this slot.
See also
pipe pipeBody
Closing and errors
Use close() to close the connection to the client. If an error occurs you're free to use killConnection.
Warning
As of now HttpClient is self-contained. This means that it will use deleteLater() on itself when the connection is closed by any side. Do not do this on your own. Never delete or deleteLater a HttpClient instance! Use close instead!
Range request and responses
If you want to support requests with 'Range' headers use rangeStart() and rangeEnd() to get the range the client requested. Use setContentLength() to set the length of the complete response.

Member Typedef Documentation

typedef QMap< QByteArray, QNetworkCookie > Nuria::HttpClient::Cookies

List of cookies.

typedef QMultiMap< QByteArray, QByteArray > Nuria::HttpClient::HeaderMap

Map used to store HTTP headers in a name -> value fashion.

Member Enumeration Documentation

The HttpHeader enum lists the most common HTTP headers for requests and responses. Read some online resource for further explanations.

Enumerator
HeaderHost 

Host, must be present in a HTTP/1.1 session.

HeaderUserAgent 

User-Agent, must be present in a HTTP/1.1 session.

The HttpVerb enum contains a list of possible HTTP request types.

See also
SlotInfo::allowedVerbs
Enumerator
InvalidVerb 

The client sent an invalid verb. This is also the default value which is present if isHeaderReady returns false.

GET 

The client issued a GET request.

POST 

The client issued a POST request.

HEAD 

The client issued a HEAD request.

PUT 

The client issued a PUT request.

DELETE 

The client issued a DELETE request.

AllVerbs 

OR-combination of all HTTP verbs.

The HttpVersion enum lists the possible HTTP versions.

Enumerator
Http1_0 

Http 1.0.

Http1_1 

Http 1.1.

Constructor & Destructor Documentation

Nuria::HttpClient::HttpClient ( HttpTransport transport,
HttpServer server 
)
explicit

Constructs a new HttpClient instance which uses transport as communication back-end. Ownership of transport is transferred to the HttpClient instance.

virtual Nuria::HttpClient::~HttpClient ( )
virtual

Destructor.

Member Function Documentation

bool Nuria::HttpClient::atEnd ( ) const
override

Returns true if the POST body has been completely read by the user. Also returns true if the request has no POST body at all. Returns false otherwise.

bool Nuria::HttpClient::bufferPostBody ( )
protected

Takes care of buffering the POST body.

void Nuria::HttpClient::close ( )
overrideslot
Note
close() will make sure that all data that is in the write buffer will be sent to the client before the socket is closed.

If no data has been sent yet, but a request header has been received, a appropriate response header will be sent.

See also
forceClose
qint64 Nuria::HttpClient::contentLength ( ) const

Returns the Content-Length. Returns -1 if the content length is unknown.

QNetworkCookie Nuria::HttpClient::cookie ( const QByteArray &  name)

Returns the value of cookie name. Returns an empty value if there is no cookie with this name.

Note
This method refers to cookies received from the client.
See also
cookies hasCookie
Cookies Nuria::HttpClient::cookies ( )

Returns all received cookies from the client.

Note
This method refers to cookies received from the client.
See also
cookie hasCookie
void Nuria::HttpClient::disconnected ( )
signal

Gets emitted when the user just closed the connection.

void Nuria::HttpClient::forceClose ( )
slot

Closes the socket without caring about the write buffer.

Warning
This may cause data-loss!
bool Nuria::HttpClient::hasCookie ( const QByteArray &  name)

Returns if there is a cookie name.

Note
This method refers to cookies received from the client.
See also
cookies cookie
bool Nuria::HttpClient::hasReadablePostBody ( ) const

Returns true only if this request has a POST body and it's readable by one of the readers known to HttpClient, e.g. for HTTP multi-part.

See also
read()
bool Nuria::HttpClient::hasRequestHeader ( const QByteArray &  key) const

Returns if the client has sent a value for key in the request header.

bool Nuria::HttpClient::hasRequestHeader ( HttpHeader  header) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

bool Nuria::HttpClient::hasResponseHeader ( const QByteArray &  key) const

Returns true when key has a value in the response header

bool Nuria::HttpClient::hasResponseHeader ( HttpHeader  header) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

void Nuria::HttpClient::headerReady ( )
signal

Gets emitted when the client has sent the header.

static QByteArray Nuria::HttpClient::httpHeaderName ( HttpHeader  header)
static

Returns the name of a HTTP standard header.

HttpServer* Nuria::HttpClient::httpServer ( ) const

Returns the HTTP server this client belongs to.

static QByteArray Nuria::HttpClient::httpStatusCodeName ( int  code)
static

Returns the HTTP name for a statuscode. If none is known for code, an empty string is returned.

bool Nuria::HttpClient::isConnectionSecure ( ) const

Returns true if the connection is secured.

See also
HttpTransport::isSecure
bool Nuria::HttpClient::isHeaderReady ( ) const

Returns true if the client has sent the complete header.

virtual bool Nuria::HttpClient::isSequential ( ) const
virtual

Returns false, meaning this is a random-access device.

Warning
If you've set a buffer device through pipeFromPostBody(), then true is returned.
bool Nuria::HttpClient::keepConnectionOpen ( ) const

Returns if the connection should be kept open after the slot has been called.

bool Nuria::HttpClient::killConnection ( int  error,
const QString &  cause = QString() 
)
slot

Kills the connection to the client immediatly with error as HTTP error code. If cause is not empty, it will be sent to the client. Else a appropriate cause is chosen automatically based on error.

This is only possible until the response header has been sent. If the response header has already been sent, the connection to the client will simply be destroyed.

QHostAddress Nuria::HttpClient::localAddress ( ) const

See QAbstractSocket::localAddress.

quint16 Nuria::HttpClient::localPort ( ) const

See QAbstractSocket::localPort.

QUrl Nuria::HttpClient::path ( ) const

Returns the complete requested path.

QHostAddress Nuria::HttpClient::peerAddress ( ) const

See QAbstractSocket::peerAddress.

quint16 Nuria::HttpClient::peerPort ( ) const

See QAbstractSocket::peerPort.

bool Nuria::HttpClient::pipeFromPostBody ( QIODevice *  device,
bool  takeOwnership = false 
)

Uses device from now on as buffer device. You can use this for example when you write an application which takes the POST body data, processes it somehow and then pipeToClient() the data back. The data in the current buffer is written to device.

Upon calling, the openMode of the HttpClient will be changed to QIODevice::WriteOnly.

Note
device must be open and writable.
Warning
Make sure device is not nullptr.
bool Nuria::HttpClient::pipeToClient ( QIODevice *  device,
qint64  maxlen = -1 
)

Takes device and pipes its contents into the client socket. After this call, any other write call will fail. The ownership of device will be transferred to this instance and thus will be destroyed when the client quits or device has no more data to read.

Note
device must be readable and open.
void Nuria::HttpClient::postBodyComplete ( )
signal

Gets emitted when the transfer of the POST body has been completed.

qint64 Nuria::HttpClient::postBodyLength ( ) const

Convenience function, returns the length of the POST body using the Content-Length header.

HttpPostBodyReader* Nuria::HttpClient::postBodyReader ( )

If hasReadablePostBody() returns true, returns a suitable POST body reader instance. Else returns nullptr. The reader instance is owned by the HttpClient. Consecutive calls of this method will always return the same result. The first call will create the reader.

qint64 Nuria::HttpClient::postBodyTransferred ( )

Returns how many bytes have been transferred of the POST body.

qint64 Nuria::HttpClient::rangeEnd ( ) const

Returns the end position of a 'range' request. If the client sent a valid 'Range' header, this method will return the end of the requested range. Else -1 is returned.

qint64 Nuria::HttpClient::rangeStart ( ) const

Returns the start position of a 'range' request. If the client sent a valid 'Range' header, this method will return the start of the requested range. Else -1 is returned.

virtual qint64 Nuria::HttpClient::readData ( char *  data,
qint64  maxlen 
)
protectedvirtual

Implementation of QIODevice::readData.

void Nuria::HttpClient::removeCookie ( const QByteArray &  name)

Removes a cookie. If the cookie is known by the client it will also removed client-side. If the cookie is only known on server-side it will only be removed from there. If no cookie name is known nothing happens.

Note
This is only possible as long the HTTP response hasn't been sent yet.
QByteArray Nuria::HttpClient::requestHeader ( const QByteArray &  key) const

Returns a value of a header from the request. If the client sent multiple values for the header, this method returns the last one. Returns an empty QByteArray if there was no header named key.

See also
hasRequestHeader
QByteArray Nuria::HttpClient::requestHeader ( HttpHeader  header) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

QList< QByteArray > Nuria::HttpClient::requestHeaders ( const QByteArray &  key) const

Returns the values of a header from the request. This method is useful for headers which may appear multiple times. Returns an empty QByteArray if there was no header named key.

See also
hasRequestHeader
QList< QByteArray > Nuria::HttpClient::requestHeaders ( HttpHeader  header) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

const HeaderMap& Nuria::HttpClient::requestHeaders ( ) const

Returns a map of received request headers.

bool Nuria::HttpClient::resolveUrl ( const QUrl &  url)
protected

Resolves the URL from the client. That means that the code tries to find the associated slot of url and calls it if possible. Returns true on success.

int Nuria::HttpClient::responseCode ( ) const

Returns the HTTP response code. Default is 200 OK

const HeaderMap& Nuria::HttpClient::responseHeaders ( ) const

Returns the current response headers.

QList< QByteArray > Nuria::HttpClient::responseHeaders ( const QByteArray &  key) const

Returns the response headers with key key.

QList< QByteArray > Nuria::HttpClient::responseHeaders ( HttpHeader  header) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

bool Nuria::HttpClient::responseHeaderSent ( ) const

Returns true if the response header has been sent. The response header will be sent on the first write call to the instance or if the sendResponseHeader method has been called explicitly.

bool Nuria::HttpClient::sendResponseHeader ( )
slot

Explicitly sends a response header to the client. Fails if the client hasn't send a request so far (isHeaderReady() returns false) or if the response header has already been sent (In this case responseHeaderSent() returns true).

bool Nuria::HttpClient::setContentLength ( qint64  length)

Sets the Content-Length. Used in conjunction with range responses.

Note
If the response header has already been sent the call will fail.
void Nuria::HttpClient::setCookie ( const QByteArray &  name,
const QByteArray &  value,
const QDateTime &  expires,
bool  secure = false 
)

Sets a cookie on the client using a HTTP header. If there is already a cookie with name, it will be overridden. If secure is true the client is avised to only send the cookie to the server if a secure connection is used.

Note
This is only possible as long the HTTP response hasn't been sent yet.
void Nuria::HttpClient::setCookie ( const QByteArray &  name,
const QByteArray &  value,
qint64  maxAge = 0,
bool  secure = false 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Sets a cookie on the client using a HTTP header. If there is already a cookie with name, it will be overridden. maxAge defines the maximum age of the cookie in seconds. If it's 0, the cookie will removed by the client at the end of the session. If secure is true the client is avised to only send the cookie to the server if a secure connection is used.

Note
This is only possible as long the HTTP response hasn't been sent yet.
If maxAge is 0 (the default), the cookie will be a session cookie.
void Nuria::HttpClient::setCookie ( const QNetworkCookie &  cookie)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Sets a cookie on the client using a HTTP header. Use this overload if the other overloads aren't specific enough.

Note
This is only possible as long the HTTP response hasn't been sent yet.
void Nuria::HttpClient::setKeepConnectionOpen ( bool  keepOpen)

Sets whether the HTTP connection should be kept open after a slot has been called. By default, this is not the case.

Warning
Ownership of the instance is transferred to the user.
Note
Call close() to delete the instance. It will initiate a graceful shutdown, making sure everything is written before the instance is deleted. If the connection is already closed, use deleteLater().
Do not combine this with pipe().
bool Nuria::HttpClient::setRangeEnd ( qint64  pos)

Sets the end position of a range response.

Note
If the response header has already been sent the call will fail.
bool Nuria::HttpClient::setRangeStart ( qint64  pos)

Sets the start position of a range response.

Note
If the response header has already been sent the call will fail.
void Nuria::HttpClient::setResponseCode ( int  code)

Sets the HTTP response code.

bool Nuria::HttpClient::setResponseHeader ( const QByteArray &  key,
const QByteArray &  value,
bool  append = false 
)

Sets a response header. Returns true if the response header has not yet been sent. If it was already sent to the client, the function will fail as HTTP doesn't allow to send additional headers after the HTTP header. In this case the response header map won't be modified. If append is true and there is already a value for key, then the new value will be appended to the list.

Note
If you want to set the 'Content-Length' header please use setContentLength().
See also
contentLength setContentLength
rangeStart rangeEnd setRangeStart setRangeEnd
bool Nuria::HttpClient::setResponseHeader ( HttpHeader  header,
const QByteArray &  value,
bool  append = false 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

bool Nuria::HttpClient::setResponseHeaders ( const HeaderMap headers)

Sets the response header map.

See also
setResponseHeader
void Nuria::HttpClient::setSlotInfo ( const SlotInfo info)

Sets a SlotInfo for this client. This is needed when you're sub-classing HttpNode with non-streaming clients.

SlotInfo Nuria::HttpClient::slotInfo ( ) const

Returns the associated slot info of the client.

HttpTransport* Nuria::HttpClient::transport ( ) const

Returns the internal HttpTransport instance.

HttpVerb Nuria::HttpClient::verb ( ) const

Returns the HTTP verb used by the client.

virtual qint64 Nuria::HttpClient::writeData ( const char *  data,
qint64  len 
)
protectedvirtual

Implementation of QIODevice::writeData.


The documentation for this class was generated from the following file: