Wt: Wt::Http::Client Class Reference

Wt 4.10.4

Loading...
Searching...
No Matches
Classes | Public Member Functions | Static Public Member Functions | List of all members
Wt::Http::Client Class Reference
HTTP protocol (Wt::Http)

An HTTP client. More...

`#include <Wt/Http/Client.h>`

Inheritance diagram for Wt::Http::Client:
[legend]

## Classes
struct | URL
| Utility class representing an URL. More...

## Public Member Functions
| Client ()
| Default constructor.
| Client (Wt::AsioWrapper::asio::io_service &ioService)
| Constructor.
virtual | ~Client ()
| Destructor.
void | setTimeout (std::chrono::steady_clock::duration timeout)
| Sets an I/O timeout.
std::chrono::steady_clock::duration | timeout () const
| Returns the I/O timeout.
void | setMaximumResponseSize (std::size_t bytes)
| Sets a maximum response size.
std::size_t | maximumResponseSize () const
| Returns the maximum response size.
void | setSslCertificateVerificationEnabled (bool enabled)
| Enables SSL certificate verification.
bool | isSslCertificateVerificationEnabled () const
| Returns whether SSL certificate verification is enabled.
void | setSslVerifyFile (const std::string &verifyFile)
| Sets a SSL certificate used for server identity verification.
void | setSslVerifyPath (const std::string &verifyPath)
| Sets a path with SSL certificates for server identity verification.
bool | get (const std::string &url)
| Starts a GET request.
bool | get (const std::string &url, const std::vector< Message::Header > headers)
| Starts a GET request.
bool | head (const std::string &url)
| Starts a HEAD request.
bool | head (const std::string &url, const std::vector< Message::Header > headers)
| Starts a HEAD request.
bool | post (const std::string &url, const Message &message)
| Starts a POST request.
bool | put (const std::string &url, const Message &message)
| Starts a PUT request.
bool | deleteRequest (const std::string &url, const Message &message)
| Starts a DELETE request.
bool | patch (const std::string &url, const Message &message)
| Starts a PATCH request.
bool | request (Http::Method method, const std::string &url, const Message &message)
| Starts a request.
void | abort ()
| Aborts the curent request.
Signal< Wt::AsioWrapper::error_code, Message > & | done ()
| Signal that is emitted when the current request is done.
Signal< Message > & | headersReceived ()
| Signal that is emitted when all response headers have been received.
Signal< std::string > & | bodyDataReceived ()
| Signal that is emitted when more body data was received.
bool | followRedirect () const
| Returns whether the client will follow redirects.
void | setFollowRedirect (bool followRedirect)
| Set whether the client will follow redirects.
int | maxRedirects () const
| Returns the maximum number of redirects to follow.
void | setMaxRedirects (int maxRedirects)
| Set the maximum number of redirects to follow.
Public Member Functions inherited from Wt::WObject
void | addChild (std::unique_ptr< WObject > child)
| Add a child WObject whose lifetime is determined by this WObject.
template<typename Child >
Child * | addChild (std::unique_ptr< Child > child)
| Add a child WObject, returning a raw pointer.
std::unique_ptr< WObject > | removeChild (WObject *child)
| Remove a child WObject, so its lifetime is no longer determined by this WObject.
template<typename Child >
std::unique_ptr< Child > | removeChild (Child *child)
| Remove a child WObject, so its lifetime is no longer determined by this WObject.
virtual const std::string | id () const
| Returns the (unique) identifier for this object.
virtual void | setObjectName (const std::string &name)
| Sets an object name.
virtual std::string | objectName () const
| Returns the object name.
void | resetLearnedSlots ()
| Resets learned stateless slot implementations.
template<class T >
void | resetLearnedSlot (void(T::*method)())
| Resets a learned stateless slot implementation.
template<class T >
WStatelessSlot * | implementStateless (void(T::*method)())
| Declares a slot to be stateless and learn client-side behaviour on first invocation.
template<class T >
WStatelessSlot * | implementStateless (void(T::*method)(), void(T::*undoMethod)())
| Declares a slot to be stateless and learn client-side behaviour in advance.
void | isNotStateless ()
| Marks the current function as not stateless.
template<class T >
WStatelessSlot * | implementJavaScript (void(T::*method)(), const std::string &jsCode)
| Provides a JavaScript implementation for a method.
Public Member Functions inherited from Wt::Core::observable
| observable () noexcept
| Default constructor.
virtual | ~observable ()
| Destructor.
template<typename... Args, typename C >
auto | bindSafe (void(C::*method)(Args...)) noexcept
| Protects a method call against object destruction.
template<typename... Args, typename C >
auto | bindSafe (void(C::*method)(Args...) const) const noexcept
| Protects a const method call against object destruction.
template<typename Function >
auto | bindSafe (const Function &function) noexcept
| Protects a function against object destruction.

## Static Public Member Functions
static bool | parseUrl (const std::string &url, URL &parsedUrl)
| Utility method to parse a URL.
Static Public Member Functions inherited from Wt::WObject

## Additional Inherited Members
Public Types inherited from Wt::WObject
typedef void(WObject::*) | Method()
| Typedef for a WObject method without arguments.
Protected Member Functions inherited from Wt::WObject
virtual WStatelessSlot * | getStateless (Method method)
| On-demand stateless slot implementation.

## Detailed Description

An HTTP client.

This class implements an HTTP client. It can be used to interact with web services using the HTTP protocol.

The client uses asynchronous I/O and only provides an asynchronous interface: you cannot actively wait for an operation to complete, instead the client will notify you of the result using the done() signal.

Because the client uses asynchronous I/O, it does its work within the scope of an event-driven thread pool implementation. By default, this is the same thread pool that is used by the Wt server, available through WServer::ioService(), but you may also use the client by providing it an explicit I/O service to be used.

The client supports the HTTP and HTTPS (if Wt was built with OpenSSL support) protocols, and can be used for GET and POST methods. One client can do only one operation at a time.

Usage example:

...
auto client = addChild(std::make_unique<Http::Client>());
client->setTimeout(std::chrono::seconds{15});
client->setMaximumResponseSize(10 * 1024);
client->done().connect(std::bind(&MyWidget::handleHttpResponse, this, _1, _2));
if (client->get("http://www.webtoolkit.eu/wt/blog/feed/"))
WApplication::instance()->deferRendering();
else {
// in case of an error in the %URL
}
}
void handleHttpResponse(std::system::error_code err, const Http::Message& response)
{
WApplication::instance()->resumeRendering();
if (!err && response.status() == 200) {
... parse response.body()
}
}
Wt::WApplication::resumeRendering
void resumeRendering()
Resumes rendering of a deferred event response.
Wt::WApplication::instance
static WApplication * instance()
Returns the current application instance.
Wt::WApplication::deferRendering
void deferRendering()
Defers rendering of the current event response.
Wt::WObject::addChild
void addChild(std::unique_ptr< WObject > child)
Add a child WObject whose lifetime is determined by this WObject.

The function connected to the done() signal will be run within the context of the application that created the client. WServer::post() is used for this.

### Basic access authentication

When you want to add authentication information in the URL, this can be done as `https://username:password@www.example.com/`. When doing this, make sure that the username and password string are URL-encoded (Wt::Utils::urlEncode). For example, `https://username:pass word@.nosp@m.www..nosp@m.examp.nosp@m.le.c.nosp@m.om/` should be passed as `https://username:pass%20word@www.example.com/`.

## Constructor & Destructor Documentation

## ◆ Client() [1/2]

Wt::Http::Client::Client | ( |  | ) |

Default constructor.

The client uses the I/O service and thread-pool from the current WApplication::instance().

## ◆ Client() [2/2]

Wt::Http::Client::Client | ( | Wt::AsioWrapper::asio::io_service & | ioService | ) |

Constructor.

The client uses the given I/O service and thread-pool, and is useful to use the client outside the context of a web application.

## ◆ ~Client()

virtual Wt::Http::Client::~Client | ( |  | ) |
| virtual

Destructor.

If the client is still busy, the current request is aborted.

See also
  abort()

## Member Function Documentation

## ◆ abort()

void Wt::Http::Client::abort | ( |  | ) |

Aborts the curent request.

If the client is currently busy, this cancels the pending request. done() will be emitted with asio::error::operation_aborted.

Note
  The abort will be performed asynchronously, so it is possible that done() is still emitted with a successful response after abort() is called.

## ◆ bodyDataReceived()

Signal< std::string > & Wt::Http::Client::bodyDataReceived | ( |  | ) |

Signal that is emitted when more body data was received.

The signal contains the next body data chunk received. You may want to catch this signal if you want to process the response as it is being received.

You may want to use this in combination with setMaximumResponseSize(0) to handle very long responses.

## ◆ deleteRequest()

bool Wt::Http::Client::deleteRequest | ( | const std::string & | url,
|  | const Message & | message )

Starts a DELETE request.

The function starts an asynchronous DELETE request, and returns immediately.

The function returns `true` when the DELETE request has been scheduled, and thus done() will be emitted eventually.

The function returns `false` if the client could not schedule the request, for example if the `url` is invalid or if the URL scheme is not supported.

See also
  request(), done()

## ◆ done()

Signal< Wt::AsioWrapper::error_code, Message > & Wt::Http::Client::done | ( |  | ) |

Signal that is emitted when the current request is done.

The `error` is 0 if the HTTP request was successful. Then, the `message` contains the result.

If the `error` is not 0, then an error message is given by `err.message()`.

Typical code to process the result is:

void handle(Wt::AsioWrapper::error_code err, const Http::Message& response)
{
if (!err) {
if (response.status() == 200) {
... success
}
} else {
Wt::log("error") << "Http::Client error: " << err.message();
}
}
Wt::Http::Message
An HTTP client message (request or response).
Definition Message.h:27
Wt::Http::Message::status
int status() const
Returns the status code.
Definition Message.h:103
Wt::WLogger::log
WLogEntry log(const std::string &type)
Logging function.

## ◆ followRedirect()

bool Wt::Http::Client::followRedirect | ( |  | ) | const

Returns whether the client will follow redirects.

See also
  setFollowRedirect

## ◆ get() [1/2]

bool Wt::Http::Client::get | ( | const std::string & | url | ) |

Starts a GET request.

The function starts an asynchronous GET request, and returns immediately.

The function returns `true` when the GET request has been scheduled, and thus done() will be emitted eventually.

The function returns `false` if the client could not schedule the request, for example if the `url` is invalid or if the URL scheme is not supported.

See also
  request(), done()

## ◆ get() [2/2]

bool Wt::Http::Client::get | ( | const std::string & | url,
|  | const std::vector< Message::Header > | headers )

Starts a GET request.

The function starts an asynchronous GET request, and returns immediately.

The function returns `true` when the GET request has been scheduled, and thus done() will be emitted eventually.

The function returns `false` if the client could not schedule the request, for example if the `url` is invalid or if the URL scheme is not supported.

This function accepts one or more headers.

See also
  request(), done()

## ◆ head() [1/2]

bool Wt::Http::Client::head | ( | const std::string & | url | ) |

Starts a HEAD request.

The function starts an asynchronous HEAD request, and returns immediately.

The function returns `true` when the HEAD request has been scheduled, and thus done() will be emitted eventually.

The function returns `false` if the client could not schedule the request, for example if the `url` is invalid or if the URL scheme is not supported.

See also
  request(), done()

## ◆ head() [2/2]

bool Wt::Http::Client::head | ( | const std::string & | url,
|  | const std::vector< Message::Header > | headers )

Starts a HEAD request.

The function starts an asynchronous HEAD request, and returns immediately.

The function returns `true` when the HEAD request has been scheduled, and thus done() will be emitted eventually.

The function returns `false` if the client could not schedule the request, for example if the `url` is invalid or if the URL scheme is not supported.

This function accepts one or more headers.

See also
  request(), done()

## ◆ headersReceived()

Signal< Message > & Wt::Http::Client::headersReceived | ( |  | ) |

Signal that is emitted when all response headers have been received.

The signal forwards the message with all headers, but with empty body text. You may want to catch this signal if you want to examine the headers prior to having received the complete message.

See also
  done(), bodyDataReceived()

## ◆ isSslCertificateVerificationEnabled()

bool Wt::Http::Client::isSslCertificateVerificationEnabled | ( |  | ) | const

Returns whether SSL certificate verification is enabled.

See also
  setSslCertificateVerificationEnabled()

## ◆ maximumResponseSize()

std::size_t Wt::Http::Client::maximumResponseSize | ( |  | ) | const

Returns the maximum response size.

See also
  setMaximumResponseSize()

## ◆ maxRedirects()

int Wt::Http::Client::maxRedirects | ( |  | ) | const

Returns the maximum number of redirects to follow.

See also
  setMaxRedirects()

## ◆ parseUrl()

static bool Wt::Http::Client::parseUrl | ( | const std::string & | url,
|  | URL & | parsedUrl )
| static

Utility method to parse a URL.

This parses a URL into an URL object.

The method returns true if the URL could be parsed successfully.

## ◆ patch()

bool Wt::Http::Client::patch | ( | const std::string & | url,
|  | const Message & | message )

Starts a PATCH request.

The function starts an asynchronous PATCH request, and returns immediately.

The function returns `true` when the PATCH request has been scheduled, and thus done() will be emitted eventually.

The function returns `false` if the client could not schedule the request, for example if the `url` is invalid or if the URL scheme is not supported.

See also
  request(), done()

## ◆ post()

bool Wt::Http::Client::post | ( | const std::string & | url,
|  | const Message & | message )

Starts a POST request.

The function starts an asynchronous POST request, and returns immediately.

The function returns `true` when the POST request has been scheduled, and thus done() will be emitted eventually.

The function returns `false` if the client could not schedule the request, for example if the `url` is invalid or if the URL scheme is not supported.

See also
  request(), done()

## ◆ put()

bool Wt::Http::Client::put | ( | const std::string & | url,
|  | const Message & | message )

Starts a PUT request.

The function starts an asynchronous PUT request, and returns immediately.

The function returns `true` when the PUT request has been scheduled, and thus done() will be emitted eventually.

The function returns `false` if the client could not schedule the request, for example if the `url` is invalid or if the URL scheme is not supported.

See also
  request(), done()

## ◆ request()

bool Wt::Http::Client::request | ( | Http::Method | method,
|  | const std::string & | url,
|  | const Message & | message )

Starts a request.

The function starts an asynchronous HTTP request, and returns immediately.

The function returns `true` when the request has been scheduled, and thus done() will be emitted eventually.

The function returns `false` if the client could not schedule the request, for example if the `url` is invalid or if the URL scheme is not supported.

See also
  request(), done()

## ◆ setFollowRedirect()

void Wt::Http::Client::setFollowRedirect | ( | bool | followRedirect | ) |

Set whether the client will follow redirects.

If set and the request method is GET, redirects are automatically followed.

## ◆ setMaximumResponseSize()

void Wt::Http::Client::setMaximumResponseSize | ( | std::size_t | bytes | ) |

Sets a maximum response size.

The response is stored in-memory. To avoid a DoS by a malicious downstream HTTP server, the response size is bounded by an upper limit.

The limit includes status line, headers and response body.

The default value is 64 kilo bytes.

A value of 0 has a special meaning: the size of the response will not be limited, but the response body will not be stored in the response message. Instead the data is made available only to bodyDataReceived() to be processed incrementally.

## ◆ setMaxRedirects()

void Wt::Http::Client::setMaxRedirects | ( | int | maxRedirects | ) |

Set the maximum number of redirects to follow.

This is used only when followRedirect() is enabled.

The default is 20.

## ◆ setSslCertificateVerificationEnabled()

void Wt::Http::Client::setSslCertificateVerificationEnabled | ( | bool | enabled | ) |

Enables SSL certificate verification.

For https requests, it is (very strongly!) recommended to perform certificate verification: this verifies that you are indeed connected to the server you intended (and not to a man-in-the-middle). Without such a check, encryption simply isn't very useful.

Nevertheless, there may be situations in which you will want to disable this functionality.

The default configuration is to have certificate verification enabled.

## ◆ setSslVerifyFile()

void Wt::Http::Client::setSslVerifyFile | ( | const std::string & | verifyFile | ) |

Sets a SSL certificate used for server identity verification.

This setting only affects a https request: it configures a certificate file to be used to verify the identity of the server.

## ◆ setSslVerifyPath()

void Wt::Http::Client::setSslVerifyPath | ( | const std::string & | verifyPath | ) |

Sets a path with SSL certificates for server identity verification.

This setting only affects a https request: it configures a directory containing certificates to be used to verify the identity of the server.

## ◆ setTimeout()

void Wt::Http::Client::setTimeout | ( | std::chrono::steady_clock::duration | timeout | ) |

Sets an I/O timeout.

This sets a timeout waiting for I/O operations. The timeout does not bound the total timeout, since the timer is reset on each I/O progress.

The default timeout is 10 seconds.

## ◆ timeout()

std::chrono::steady_clock::duration Wt::Http::Client::timeout | ( |  | ) | const

Returns the I/O timeout.

See also
  setTimeout()