identt
HttpClient.hpp
Go to the documentation of this file.
1 
33 #ifndef _IDENTT_HTTP_HTTPCLIENT_HPP_
34 #define _IDENTT_HTTP_HTTPCLIENT_HPP_
35 
36 #include "HttpClientBase.hpp"
37 
38 #ifdef IDENTT_BUILD_WITH_SSL
39 #include <boost/asio/ssl.hpp>
40 #endif
41 
42 namespace identt {
43 namespace http {
44 
45 template<class socket_type>
46 class HttpClient : public ClientBase<socket_type> {};
47 
48 typedef boost::asio::ip::tcp::socket HTTP;
49 
50 template<>
51 class HttpClient<HTTP> : public ClientBase<HTTP> {
52 public:
53  HttpClient(const std::string& server_port_path) : ClientBase<HTTP>::ClientBase(server_port_path, 80)
54  {
55  socket=std::make_shared<HTTP>(asio_io_service);
56  }
57 
58 private:
59  void connect()
60  {
61  if(socket_error || !socket->is_open()) {
62  boost::asio::ip::tcp::resolver::query query(host, std::to_string(port));
63  boost::asio::connect(*socket, asio_resolver.resolve(query));
64 
65  boost::asio::ip::tcp::no_delay option(true);
66  socket->set_option(option);
67 
68  socket_error=false;
69  }
70  }
71 };
72 
73 #ifdef IDENTT_BUILD_WITH_SSL
74 typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> HTTPS;
75 template<>
76 class HttpClient<HTTP> : public ClientBase<HTTPS> {
77 public:
78  HttpClient(const std::string& server_port_path, bool verify_certificate=true,
79  const std::string& cert_file=std::string(), const std::string& private_key_file=std::string(),
80  const std::string& verify_file=std::string()) :
81  ClientBase<HTTPS>::ClientBase(server_port_path, 443), asio_context(boost::asio::ssl::context::sslv23)
82  {
83  if(verify_certificate)
84  asio_context.set_verify_mode(boost::asio::ssl::verify_peer);
85  else
86  asio_context.set_verify_mode(boost::asio::ssl::verify_none);
87 
88  if(cert_file.size()>0 && private_key_file.size()>0) {
89  asio_context.use_certificate_chain_file(cert_file);
90  asio_context.use_private_key_file(private_key_file, boost::asio::ssl::context::pem);
91  }
92 
93  if(verify_file.size()>0)
94  asio_context.load_verify_file(verify_file);
95 
96  socket=std::make_shared<HTTPS>(asio_io_service, asio_context);
97  };
98 
99 private:
100  boost::asio::ssl::context asio_context;
101 
102  void connect()
103  {
104  if(socket_error || !socket->lowest_layer().is_open()) {
105  boost::asio::ip::tcp::resolver::query query(host, std::to_string(port));
106  boost::asio::connect(socket->lowest_layer(), asio_resolver.resolve(query));
107 
108  boost::asio::ip::tcp::no_delay option(true);
109  socket->lowest_layer().set_option(option);
110 
111  socket->handshake(boost::asio::ssl::stream_base::client);
112  socket_error=false;
113  }
114  }
115 };
116 #endif
117 
118 } // namespace webserver
119 } // namespace identt
120 #endif /* _IDENTT_HTTP_HTTPCLIENT_HPP_ */
Definition: CryptoBase.hpp:49
Definition: HttpClientBase.hpp:44
Definition: HttpClient.hpp:46