http_client.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * client.h
  3. *
  4. * Created on: 2021年8月16日
  5. * Author: pengzc
  6. */
  7. #ifndef JNI_HTTP_CLIENT_H_
  8. #define JNI_HTTP_CLIENT_H_
  9. #include <cstdlib>
  10. #include <cctype>
  11. #include <string>
  12. #include "http_request.h"
  13. #include "http_response.h"
  14. #include "curl/curl.h"
  15. #include <system/Thread.h>
  16. #include <functional>
  17. namespace base {
  18. class HttpClient {
  19. public:
  20. HttpClient();
  21. virtual ~HttpClient();
  22. typedef std::function<int (int64_t dltotal,
  23. int64_t dlnow, int64_t ultotal, int64_t ulnow)> ProgressCallback;
  24. HttpResponse Do(const HttpRequest& request);
  25. HttpResponse Do(const HttpRequest& request, ProgressCallback progress);
  26. HttpResponse Do(const HttpRequest& request, const std::string& save_path,
  27. ProgressCallback progress);
  28. /**
  29. * 连接超时
  30. */
  31. HttpClient& SetConnectionTimeout(int ms);
  32. /**
  33. * 总超时
  34. */
  35. HttpClient& SetTimeout(int ms);
  36. /**
  37. * 速度低于bytes/s,持续seconds,中止执行
  38. */
  39. HttpClient& SetLowSpeedLimit(int bytes, int seconds);
  40. void SetCAInfoFilePath(const std::string& caInfoFilePath);
  41. void SetSSLVerify(bool verify);
  42. /**
  43. * 终止请求
  44. */
  45. void Abort();
  46. void SetDebug(bool debug);
  47. private:
  48. static ::size_t curl_response_write_callback(void *data, ::size_t size,
  49. ::size_t nmemb, void *userdata);
  50. static ::size_t header_callback(void *data, ::size_t size, ::size_t nmemb,
  51. void *userdata);
  52. static int curl_progress_callback(void *clientp, curl_off_t dltotal,
  53. curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow);
  54. static int debug_trace(CURL *handle, curl_infotype type, char *data, ::size_t size,
  55. void *userp);
  56. private:
  57. CURL* curl_;
  58. int connection_timeout_;
  59. int timeout_;
  60. std::string ca_info_file_path_;
  61. bool ssl_verify_;
  62. bool aborted_;
  63. ProgressCallback progress_callback_;
  64. Mutex do_mutex_;
  65. struct {
  66. int bytes;
  67. int seconds;
  68. }low_speed_limit_;
  69. bool debug_;
  70. };
  71. } /* namespace base */
  72. #endif /* JNI_HTTP_CLIENT_H_ */