HTTPClient.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #ifndef BELL_HTTP_CLIENT
  2. #define BELL_HTTP_CLIENT
  3. #include "BellSocket.h"
  4. #include "ByteStream.h"
  5. #include "TCPSocket.h"
  6. #include "TLSSocket.h"
  7. #include <map>
  8. #include <memory>
  9. #include <string>
  10. #define BUF_SIZE 128
  11. namespace bell {
  12. class HTTPClient {
  13. public:
  14. enum HTTPMethod {
  15. GET,
  16. POST,
  17. };
  18. struct HTTPRequest {
  19. HTTPMethod method = HTTPMethod::GET;
  20. std::string url;
  21. const char *body = nullptr;
  22. const char *contentType = nullptr;
  23. std::map<std::string, std::string> headers;
  24. int maxRedirects = -1;
  25. std::ostream *dumpFs = nullptr;
  26. std::ostream *dumpRawFs = nullptr;
  27. };
  28. struct HTTPResponse : public ByteStream {
  29. std::shared_ptr<bell::Socket> socket;
  30. std::map<std::string, std::string> headers;
  31. uint16_t statusCode;
  32. uint32_t contentLength;
  33. std::string contentType;
  34. std::string location;
  35. bool isChunked = false;
  36. bool isGzip = false;
  37. bool isComplete = false;
  38. bool isRedirect = false;
  39. uint8_t redirectCount = 0;
  40. std::ostream *dumpFs = nullptr;
  41. std::ostream *dumpRawFs = nullptr;
  42. ~HTTPResponse();
  43. void close() override;
  44. void readHeaders();
  45. uint32_t read(char *dst, uint32_t len, bool wait = false);
  46. std::string readToString();
  47. inline size_t skip(size_t len) override {
  48. return (size_t)read((char *)nullptr, len);
  49. }
  50. inline size_t read(uint8_t *dst, size_t len) override {
  51. return (size_t)read((char *)dst, len, false);
  52. }
  53. inline uint32_t read(uint8_t *dst, uint32_t len, bool wait) {
  54. return read((char *)dst, len, wait);
  55. }
  56. inline size_t size() override {
  57. return (size_t)contentLength;
  58. }
  59. inline size_t position() override {
  60. return (size_t)bodyRead;
  61. }
  62. private:
  63. char *buf = nullptr; // allocated buffer
  64. char *bufPtr = nullptr; // reading pointer within buf
  65. uint32_t bodyRead = 0;
  66. uint32_t bufRemaining = 0;
  67. uint32_t chunkRemaining = 0;
  68. bool isStreaming = false;
  69. uint32_t readRaw(char *dst);
  70. bool skipRaw(uint32_t len, bool dontRead = false);
  71. };
  72. typedef std::unique_ptr<struct HTTPClient::HTTPResponse> HTTPResponse_t;
  73. private:
  74. static HTTPResponse_t executeImpl(const struct HTTPRequest &request, HTTPResponse_t response);
  75. static bool readHeader(const char *&header, const char *name);
  76. public:
  77. static HTTPResponse_t execute(const struct HTTPRequest &request);
  78. };
  79. typedef std::unique_ptr<struct HTTPClient::HTTPResponse> HTTPResponse_t;
  80. } // namespace bell
  81. #endif