HTTPClient.h 1.6 KB

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