You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.8 KiB
C

#ifndef WEBCC_HTTP_CLIENT_H_
#define WEBCC_HTTP_CLIENT_H_
8 years ago
#include <cassert>
7 years ago
#include <memory>
#include <vector>
7 years ago
#include "boost/asio/deadline_timer.hpp"
#include "boost/asio/io_context.hpp"
#include "boost/asio/ip/tcp.hpp"
#include "webcc/globals.h"
#include "webcc/http_request.h"
#include "webcc/http_response.h"
7 years ago
#include "webcc/http_response_parser.h"
8 years ago
namespace webcc {
8 years ago
// HTTP client session in synchronous mode.
// A request will not return until the response is received or timeout occurs.
// Don't use the same HttpClient object in multiple threads.
8 years ago
class HttpClient {
public:
8 years ago
HttpClient();
7 years ago
~HttpClient() = default;
DELETE_COPY_AND_ASSIGN(HttpClient);
// Set the timeout seconds for reading response.
// The |seconds| is only effective when greater than 0.
void SetTimeout(int seconds);
// Connect to server, send request, wait until response is received.
bool Request(const HttpRequest& request);
HttpResponsePtr response() const { return response_; }
bool timed_out() const { return timed_out_; }
Error error() const { return error_; }
private:
7 years ago
Error Connect(const HttpRequest& request);
Error SendReqeust(const HttpRequest& request);
Error ReadResponse();
7 years ago
void DoReadResponse(Error* error);
void AsyncWaitDeadline();
void DeadlineHandler(boost::system::error_code ec);
8 years ago
void Stop();
boost::asio::io_context io_context_;
7 years ago
boost::asio::ip::tcp::socket socket_;
std::vector<char> buffer_;
7 years ago
HttpResponsePtr response_;
std::unique_ptr<HttpResponseParser> response_parser_;
boost::asio::deadline_timer deadline_;
7 years ago
// Maximum seconds to wait before the client cancels the operation.
// Only for reading response from server.
int timeout_seconds_;
7 years ago
bool stopped_;
// If the error was caused by timeout or not.
bool timed_out_;
Error error_;
8 years ago
};
} // namespace webcc
8 years ago
#endif // WEBCC_HTTP_CLIENT_H_