Skip to content

Recipe: Interceptors

Himanshu Shekhar edited this page Oct 4, 2017 · 1 revision

EasyHttp also includes Interceptors, inspired by okHttp's Interceptors to hack into Http requests/responses in order to monitor/debug, rewrite and retry them. Just like okHttp, EasyHttp also supports interceptors at both the Application and Network level (see okHttp wiki for details).

As an example, we have included a simple logging interceptor which logs every request made to console when the library is used in the debug mode. Here's how you can configure the default Logging interceptor.

try {
    easyhttpcpp::LoggingInterceptorFactory loggingInterceptorFactory;

    // configure logging interceptors
    easyhttpcpp::EasyHttp::Builder httpClientBuilder;
    // log every call made to http client in debug mode
    httpClientBuilder.addInterceptor(loggingInterceptorFactory.interceptor(easyhttpcpp::LoggingInterceptorTypeCall))
            // log every network request in debug mode
            .addNetworkInterceptor(loggingInterceptorFactory.interceptor(easyhttpcpp::LoggingInterceptorTypeNetwork));

    // create http client
    easyhttpcpp::EasyHttp::Ptr pHttpClient = httpClientBuilder.build();

    // create a new request and execute synchronously
    easyhttpcpp::Request::Builder requestBuilder;
    easyhttpcpp::Request::Ptr pRequest = requestBuilder.setUrl("https://github.com/sony/easyhttpcpp").build();
    easyhttpcpp::Call::Ptr pCall = pHttpClient->newCall(pRequest);
    easyhttpcpp::Response::Ptr pResponse = pCall->execute();

    if (!pResponse->isSuccessful()) {
        std::cout << "HTTP GET Error: (" << pResponse->getCode() << ")" << std::endl;
    } else {
        std::cout << "HTTP GET Success!" << std::endl;
    }

    // dump response
    dumpResponse(pResponse);
} catch (const std::exception& e) {
    std::cout << "Error occurred: " << e.what() << std::endl;
}
Clone this wiki locally