HttpClientHelper.h (2629B)
1 // Copyright (c) Microsoft Corporation. 2 // Licensed under the MIT License. 3 #pragma once 4 #include <winget/Certificates.h> 5 #include <cpprest/http_client.h> 6 #include <cpprest/json.h> 7 #include <optional> 8 #include <vector> 9 10 namespace AppInstaller::Http 11 { 12 struct HttpClientHelper 13 { 14 using HttpRequestHeaders = std::unordered_map<utility::string_t, utility::string_t>; 15 16 struct HttpResponseHandlerResult 17 { 18 // The custom response handler result. Default is empty. 19 std::optional<web::json::value> Result = std::nullopt; 20 21 // Indicates whether to use default handling logic by HttpClientHelper instead (i.e. the custom response handler does not handle the specific response). 22 bool UseDefaultHandling = false; 23 }; 24 25 using HttpResponseHandler = std::function<HttpResponseHandlerResult(const web::http::http_response&)>; 26 27 HttpClientHelper(std::shared_ptr<web::http::http_pipeline_stage> = {}); 28 29 pplx::task<web::http::http_response> Post(const utility::string_t& uri, const web::json::value& body, const HttpRequestHeaders& headers = {}, const HttpRequestHeaders& authHeaders = {}) const; 30 31 std::optional<web::json::value> HandlePost(const utility::string_t& uri, const web::json::value& body, const HttpRequestHeaders& headers = {}, const HttpRequestHeaders& authHeaders = {}, const HttpResponseHandler& customHandler = {}) const; 32 33 pplx::task<web::http::http_response> Get(const utility::string_t& uri, const HttpRequestHeaders& headers = {}, const HttpRequestHeaders& authHeaders = {}) const; 34 35 std::optional<web::json::value> HandleGet(const utility::string_t& uri, const HttpRequestHeaders& headers = {}, const HttpRequestHeaders& authHeaders = {}, const HttpResponseHandler& customHandler = {}) const; 36 37 void SetPinningConfiguration(const Certificates::PinningConfiguration& configuration); 38 39 protected: 40 std::optional<web::json::value> ValidateAndExtractResponse(const web::http::http_response& response) const; 41 42 std::optional<web::json::value> ExtractJsonResponse(const web::http::http_response& response) const; 43 44 private: 45 web::http::client::http_client GetClient(const utility::string_t& uri) const; 46 47 // Translates a cpprestsdk http_exception to a WIL exception. 48 static void RethrowAsWilException(const web::http::http_exception& exception); 49 50 std::shared_ptr<web::http::http_pipeline_stage> m_defaultRequestHandlerStage; 51 web::http::client::http_client_config m_clientConfig; 52 }; 53 }