class EE::Network::Http

Overview

A HTTP client. More…

#include <http.hpp>

class Http: private EE::NonCopyable {
public:
    // typedefs

    typedef std::function<void(const Http&, Http::Request&, Http::Response&)> AsyncResponseCallback;

    // classes

    class AsyncRequest;
    class HttpConnection;
    class MultipartEntitiesBuilder;
    class Pool;
    class Request;
    class Response;

    // construction

    Http();
    Http(const std::string& host, unsigned short port = 0, bool useSSL = false, URI proxy = URI());
    ~Http();

    // methods

    void setHost(const std::string& host, unsigned short port = 0, bool useSSL = false, URI proxy = URI());
    Response sendRequest(const Request& request, Time timeout = Time::Zero);
    Response downloadRequest(const Request& request, IOStream& writeTo, Time timeout = Time::Zero);
    Response downloadRequest(const Request& request, std::string writePath, Time timeout = Time::Zero);
    void sendAsyncRequest(const AsyncResponseCallback& cb, const Http::Request& request, Time timeout = Time::Zero);
    void downloadAsyncRequest(const AsyncResponseCallback& cb, const Http::Request& request, IOStream& writeTo, Time timeout = Time::Zero);
    void downloadAsyncRequest(const AsyncResponseCallback& cb, const Http::Request& request, std::string writePath, Time timeout = Time::Zero);
    const IpAddress& getHost() const;
    const std::string& getHostName() const;
    const unsigned short& getPort() const;
    const bool& isSSL() const;
    URI getURI() const;
    void setProxy(const URI& uri);
    const URI& getProxy() const;
    bool isProxied() const;

    static Response request(
        const URI& uri,
        Request::Method method = Request::Method::Get,
        const Time& timeout = Time::Zero,
        const Request::ProgressCallback& progressCallback = Request::ProgressCallback(),
        const Request::FieldTable& headers = Request::FieldTable(),
        const std::string& body = "",
        const bool& validateCertificate = true,
        const URI& proxy = URI()
    );

    static Response get(
        const URI& uri,
        const Time& timeout = Time::Zero,
        const Request::ProgressCallback& progressCallback = Request::ProgressCallback(),
        const Request::FieldTable& headers = Request::FieldTable(),
        const std::string& body = "",
        const bool& validateCertificate = true,
        const URI& proxy = URI()
    );

    static Response post(
        const URI& uri,
        const Time& timeout = Time::Zero,
        const Request::ProgressCallback& progressCallback = Request::ProgressCallback(),
        const Request::FieldTable& headers = Request::FieldTable(),
        const std::string& body = "",
        const bool& validateCertificate = true,
        const URI& proxy = URI()
    );

    static void requestAsync(
        const Http::AsyncResponseCallback& cb,
        const URI& uri,
        const Time& timeout = Time::Zero,
        Request::Method method = Request::Method::Get,
        const Request::ProgressCallback& progressCallback = Request::ProgressCallback(),
        const Request::FieldTable& headers = Request::FieldTable(),
        const std::string& body = "",
        const bool& validateCertificate = true,
        const URI& proxy = URI()
    );

    static void getAsync(
        const Http::AsyncResponseCallback& cb,
        const URI& uri,
        const Time& timeout = Time::Zero,
        const Request::ProgressCallback& progressCallback = Request::ProgressCallback(),
        const Request::FieldTable& headers = Request::FieldTable(),
        const std::string& body = "",
        const bool& validateCertificate = true,
        const URI& proxy = URI()
    );

    static void postAsync(
        const Http::AsyncResponseCallback& cb,
        const URI& uri,
        const Time& timeout = Time::Zero,
        const Request::ProgressCallback& progressCallback = Request::ProgressCallback(),
        const Request::FieldTable& headers = Request::FieldTable(),
        const std::string& body = "",
        const bool& validateCertificate = true,
        const URI& proxy = URI()
    );

    static URI getEnvProxyURI();
    static void setThreadPool(std::shared_ptr<ThreadPool> pool);
};

Detailed Documentation

A HTTP client.

Http is a very simple HTTP client that allows you to communicate with a web server. You can retrieve web pages, send data to an interactive resource, download a remote file, etc. The HTTP client is split into 3 classes:

  • EE::Network::Http::Request

  • EE::Network::Http::Response

  • EE::Network::Http EE::Network::Http::Request builds the request that will be sent to the server. A request is made of:

  • a method (what you want to do)

  • a target URI (usually the name of the web page or file)

  • one or more header fields (options that you can pass to the server)

  • an optional body (for POST requests) EE::Network::Http::Response parse the response from the web server and provides getters to read them. The response contains:

  • a status code

  • header fields (that may be answers to the ones that you requested)

  • a body, which contains the contents of the requested resource Http provides a simple function, sendRequest, to send a EE::Network::Http::Request and return the corresponding EE::Network::Http::Response from the server. Usage example:

    // Create a new HTTP client
    Http http;
    
    // We'll work on http://www.google.com
    http.setHost( "http://www.google.com" );
    
    // Prepare a request to get the 'features.php' page
    Http::Request request( "features.php" );
    
    // Send the request
    Http::Response response = http.sendRequest(request);
    
    // Check the status code and display the result
    Http::Response::Status status = response.getStatus();
    if ( status == Http::Response::Ok ) {
        std::cout << response.getBody() << std::endl;
    } else {
        std::cout << "Error " << status << std::endl;
    }

Shorthand methods are also provided:

Http::Response response = Http::get( "http://www.google.com" );
if ( response.getStatus() == Http::Response::Ok ) {
    std::cout << response.getBody() << std::endl;
} else {
    std::cout << "Error " << response.getStatus() << std::endl;
}

You can also use the shorthand async alternative method:

Http::getAsync(
    [=]( const Http&, Http::Request&, Http::Response& response ) {
        if ( response.getStatus() ==  Http::Response::Ok) {
            std::cout << response.getBody() << std::endl;
        } else {
            std::cout << "Error " << response.getStatus() << std::endl;
        }
    }, "http://www.google.com" );

Typedefs

typedef std::function<void(const Http&, Http::Request&, Http::Response&)> AsyncResponseCallback

Definition of the async callback response

Construction

Http()

Default constructor.

Http(const std::string& host, unsigned short port = 0, bool useSSL = false, URI proxy = URI())

Construct the HTTP client with the target host This is equivalent to calling setHost(host, port). The port has a default value of 0, which means that the HTTP client will use the right port according to the protocol used (80 for HTTP, 443 for HTTPS). You should leave it like this unless you really need a port other than the standard one, or use an unknown protocol.

Parameters:

host

Web server to connect to

port

Port to use for connection

useSSL

force the SSL usage ( if compiled with the support of it ). If the host starts with https:// it will use it by default.

proxy

Set an http proxy for the host connection

Methods

void setHost(const std::string& host, unsigned short port = 0, bool useSSL = false, URI proxy = URI())

Set the target host This function just stores the host address and port, it doesn’t actually connect to it until you send a request. The port has a default value of 0, which means that the HTTP client will use the right port according to the protocol used (80 for HTTP, 443 for HTTPS). You should leave it like this unless you really need a port other than the standard one, or use an unknown protocol.

Parameters:

host

Web server to connect to

port

Port to use for connection

useSSL

force the SSL usage ( if compiled with the support of it ). If the host starts with https:// it will use it by default. *

proxy

Set an http proxy for the host connection

Response sendRequest(const Request& request, Time timeout = Time::Zero)

Send a HTTP request and return the server’s response. You must have a valid host before sending a request (see setHost). Any missing mandatory header field in the request will be added with an appropriate value. Warning: this function waits for the server’s response and may not return instantly; use a thread if you don’t want to block your application, or use a timeout to limit the time to wait. A value of Time::Zero means that the client will use the system defaut timeout (which is usually pretty long).

Parameters:

request

Request to send

timeout

Maximum time to wait

Returns:

Server’s response

Response downloadRequest(const Request& request, IOStream& writeTo, Time timeout = Time::Zero)

Send a HTTP request and writes the server’s response to a IOStream file. You must have a valid host before sending a request (see setHost). Any missing mandatory header field in the request will be added with an appropriate value. Warning: this function waits for the server’s response and may not return instantly; use a thread if you don’t want to block your application, or use a timeout to limit the time to wait. A value of Time::Zero means that the client will use the system defaut timeout (which is usually pretty long).

Parameters:

request

Request to send

writeTo

The IO stream to write the downloaded content

timeout

Maximum time to wait

Returns:

Server’s response

Response downloadRequest(const Request& request, std::string writePath, Time timeout = Time::Zero)

Send a HTTP request and writes the server’s response to a file system path. You must have a valid host before sending a request (see setHost). Any missing mandatory header field in the request will be added with an appropriate value. Warning: this function waits for the server’s response and may not return instantly; use a thread if you don’t want to block your application, or use a timeout to limit the time to wait. A value of Time::Zero means that the client will use the system defaut timeout (which is usually pretty long).

Parameters:

request

Request to send

writePath

The path of the file to write the downloaded content

timeout

Maximum time to wait

Returns:

Server’s response

void sendAsyncRequest(const AsyncResponseCallback& cb, const Http::Request& request, Time timeout = Time::Zero)

Sends the request and creates a new thread, when got the response informs the result to the callback. * This function does not lock the caller thread.

See also:

sendRequest

void downloadAsyncRequest(const AsyncResponseCallback& cb, const Http::Request& request, IOStream& writeTo, Time timeout = Time::Zero)

Sends the request and creates a new thread, when got the response informs the result to the callback. * This function does not lock the caller thread.

See also:

downloadRequest

void downloadAsyncRequest(const AsyncResponseCallback& cb, const Http::Request& request, std::string writePath, Time timeout = Time::Zero)

Sends the request and creates a new thread, when got the response informs the result to the callback. * This function does not lock the caller thread.

See also:

downloadRequest

const IpAddress& getHost() const

Returns:

The host address

const std::string& getHostName() const

Returns:

The host name

const unsigned short& getPort() const

Returns:

The host port

const bool& isSSL() const

Returns:

If the HTTP client uses SSL/TLS

URI getURI() const

Returns:

The URI from the schema + hostname + port

void setProxy(const URI& uri)

Sets the request proxy

const URI& getProxy() const

Returns:

The request proxy

bool isProxied() const

Returns:

Is a proxy is need to be used

static Response request(
    const URI& uri,
    Request::Method method = Request::Method::Get,
    const Time& timeout = Time::Zero,
    const Request::ProgressCallback& progressCallback = Request::ProgressCallback(),
    const Request::FieldTable& headers = Request::FieldTable(),
    const std::string& body = "",
    const bool& validateCertificate = true,
    const URI& proxy = URI()
)

Creates an HTTP Request using the global HTTP Client Pool

static Response get(
    const URI& uri,
    const Time& timeout = Time::Zero,
    const Request::ProgressCallback& progressCallback = Request::ProgressCallback(),
    const Request::FieldTable& headers = Request::FieldTable(),
    const std::string& body = "",
    const bool& validateCertificate = true,
    const URI& proxy = URI()
)

Creates an HTTP GET Request using the global HTTP Client Pool

static Response post(
    const URI& uri,
    const Time& timeout = Time::Zero,
    const Request::ProgressCallback& progressCallback = Request::ProgressCallback(),
    const Request::FieldTable& headers = Request::FieldTable(),
    const std::string& body = "",
    const bool& validateCertificate = true,
    const URI& proxy = URI()
)

Creates an HTTP POST Request using the global HTTP Client Pool

static void requestAsync(
    const Http::AsyncResponseCallback& cb,
    const URI& uri,
    const Time& timeout = Time::Zero,
    Request::Method method = Request::Method::Get,
    const Request::ProgressCallback& progressCallback = Request::ProgressCallback(),
    const Request::FieldTable& headers = Request::FieldTable(),
    const std::string& body = "",
    const bool& validateCertificate = true,
    const URI& proxy = URI()
)

Creates an async HTTP Request using the global HTTP Client Pool

static void getAsync(
    const Http::AsyncResponseCallback& cb,
    const URI& uri,
    const Time& timeout = Time::Zero,
    const Request::ProgressCallback& progressCallback = Request::ProgressCallback(),
    const Request::FieldTable& headers = Request::FieldTable(),
    const std::string& body = "",
    const bool& validateCertificate = true,
    const URI& proxy = URI()
)

Creates an async HTTP GET Request using the global HTTP Client Pool

static void postAsync(
    const Http::AsyncResponseCallback& cb,
    const URI& uri,
    const Time& timeout = Time::Zero,
    const Request::ProgressCallback& progressCallback = Request::ProgressCallback(),
    const Request::FieldTable& headers = Request::FieldTable(),
    const std::string& body = "",
    const bool& validateCertificate = true,
    const URI& proxy = URI()
)

Creates an async HTTP POST Request using the global HTTP Client Pool

static URI getEnvProxyURI()

It will try to get the proxy from the environment variables.

static void setThreadPool(std::shared_ptr<ThreadPool> pool)

Set the thread pool to consume for async requests, otherwise it will use its own