RestfulFunc.h 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. #ifndef _OTHER_RESFULFUNCEXPORT_HEADER_
  2. #define _OTHER_RESFULFUNCEXPORT_HEADER_
  3. #pragma once
  4. #ifdef _WIN32
  5. #ifdef RESTFULPUBLIC_EXPORTS
  6. #ifndef RESTFULFUNC_API
  7. #define RESTFULFUNC_API __declspec(dllexport)
  8. #endif
  9. #else
  10. #ifndef RESTFULFUNC_API
  11. #define RESTFULFUNC_API __declspec(dllimport)
  12. #endif
  13. #endif
  14. #else
  15. #if ( defined(__GNUC__) && __GNUC__ >= 4 )
  16. #define RESTFULFUNC_API __attribute__((visibility("default")))
  17. #else
  18. #define RESTFULFUNC_API
  19. #endif
  20. #endif
  21. #include <iostream>
  22. #include <string>
  23. #include <map>
  24. #include <vector>
  25. #include <sstream>
  26. /*
  27. * > 0 : 网站返回的错误码,比如 200,404 等
  28. * -1:未归类,具体错误信息见 out_msg 返回的内容
  29. * -2:超时
  30. * -3:地址不符合规范
  31. */
  32. typedef void (*restFul_GetTokenCallBack)(char *, char *, char*, char*);
  33. RESTFULFUNC_API int HttpProbe(const std::string& url, std::string& out_msg, uint32_t wait_max_secs = (uint32_t)-1);
  34. /*!
  35. * @brief Ping protocols
  36. * @param[in]
  37. * @param[out]
  38. * @return : 0: ping connect succ; 1: ping failed
  39. */
  40. RESTFULFUNC_API int PingTest(const std::string& dst_ip);
  41. RESTFULFUNC_API int SocketConnectTest(const std::string& addrIP, int nPort, std::string& out_msg);
  42. enum HttpRequestMethod
  43. {
  44. GET,
  45. POST,
  46. PUT,
  47. DEL,
  48. HEAD,
  49. OPTIONS,
  50. TRCE,
  51. CONNECT,
  52. MERGE,
  53. PATCH,
  54. UPLOAD,
  55. DOWNLOAD
  56. };
  57. enum HttpStatusCode : int
  58. {
  59. Continue = 100,
  60. SwitchingProtocols = 101,
  61. OK = 200,
  62. Created = 201,
  63. Accepted = 202,
  64. NonAuthInfo = 203,
  65. NoContent = 204,
  66. ResetContent = 205,
  67. PartialContent = 206,
  68. MultiStatus = 207,
  69. AlreadyReported = 208,
  70. MultipleChoices = 300,
  71. MovedPermanently = 301,
  72. Found = 302,
  73. SeeOther = 303,
  74. NotModified = 304,
  75. UseProxy = 305,
  76. Forbidden = 403,
  77. NotFound = 404,
  78. ServiceUnavailable = 503
  79. };
  80. struct HttpClientResponseResult
  81. {
  82. int statusCode;
  83. std::string content;
  84. HttpClientResponseResult() :statusCode(HttpStatusCode::NotFound), content("") {}
  85. /** 子类继承实现 */
  86. virtual bool ResponseOK() const
  87. {
  88. return (statusCode == HttpStatusCode::OK);
  89. }
  90. virtual std::string WhatError() const
  91. {
  92. if (statusCode <= 0) {
  93. return content;
  94. } else {
  95. std::ostringstream oss;
  96. oss << "statusCode: " << statusCode;
  97. return oss.str();
  98. }
  99. }
  100. };
  101. struct HttpClientRequestConfig
  102. {
  103. /*!
  104. * @brief
  105. * @param[in] uri: 必须以 "http://" 或 "https://" 开头
  106. * @param[out]
  107. * @return :
  108. */
  109. HttpClientRequestConfig(const std::string& uri, restFul_GetTokenCallBack t_getToken)
  110. :mMethod(HttpRequestMethod::GET), mUri(uri), mToValidCert(false)
  111. , mBodyContent(""), mContentType(""), mHeaderAcceptType("application/json"), mTimeoutSecs(0), m_withToken(true)
  112. {
  113. InitGetToken(t_getToken);
  114. }
  115. HttpClientRequestConfig(HttpRequestMethod method, restFul_GetTokenCallBack t_getToken)
  116. : mMethod(method), mToValidCert(false), mBodyContent(""), mHeaderAcceptType("application/json"), m_withToken(true)
  117. , mContentType(""), mTimeoutSecs(0)
  118. {
  119. InitGetToken(t_getToken);
  120. }
  121. HttpClientRequestConfig(HttpRequestMethod method, const std::string& uri, restFul_GetTokenCallBack t_getToken)
  122. :mMethod(method), mUri(uri), mToValidCert(false), mBodyContent(""), m_withToken(true)
  123. , mContentType(""), mHeaderAcceptType("application/json"), mTimeoutSecs(0)
  124. {
  125. InitGetToken(t_getToken);
  126. }
  127. void SetRequestType(HttpRequestMethod method) { mMethod = method; }
  128. HttpRequestMethod GetRequestType() const { return mMethod; }
  129. // uri: 必须以 "http://" 或 "https://" 开头
  130. void SetUri(const std::string& uri) { mUri = uri; }
  131. void SetChildUri(const std::string& subUri) { mSubUri = subUri; }
  132. void AppendQuery(const std::string& name, const std::string& value) {
  133. mQueryPairs[name] = value;
  134. }
  135. std::string GetBaseUri() const { return mUri; }
  136. std::string GetSubUri() const { return mSubUri; }
  137. std::string GetRequestUri() const { return mUri + mSubUri; }
  138. void ResetQuery() { mQueryPairs.clear(); }
  139. const std::map<std::string, std::string>& GetQueryPairs() const { return mQueryPairs; }
  140. std::string GetAcceptType() const { return mHeaderAcceptType; }
  141. void SetAcceptType(const std::string& value) {
  142. mHeaderAcceptType = value;
  143. }
  144. bool NeedValidCert() const { return mToValidCert; }
  145. void SetJsonBody(const std::string& value) {
  146. SetBodyContent(value, "application/json");
  147. }
  148. void SetBodyContent(const std::string& value, const std::string& type) {
  149. mBodyContent = value;
  150. mContentType = type;
  151. }
  152. virtual std::string GetBodyContent() const { return mBodyContent; }
  153. virtual std::string GetContentType() const { return mContentType; }
  154. void SetTimeout(uint32_t timeoutSecs) { mTimeoutSecs = timeoutSecs; }
  155. uint32_t GetTimeout() const { return mTimeoutSecs; }
  156. virtual void PreDo() {}
  157. virtual void PostDo() {}
  158. bool getToken(std::string & t_channelId, std::string &t_token, std::string& t_terminalNo, std::string& t_reserve1) const {
  159. char channelId[256] = "";
  160. char token[256] = "";
  161. char terminalNo[256] = "";
  162. char reserve1[256] = "";
  163. if (m_withToken && g_tokenCall != NULL)
  164. {
  165. g_tokenCall(channelId, token, terminalNo, reserve1);
  166. if (std::string(channelId).length() > 0 && std::string(token).length() > 0)
  167. {
  168. t_channelId = channelId;
  169. t_token = token;
  170. t_terminalNo = terminalNo;
  171. return true;
  172. }
  173. }
  174. return false;
  175. }
  176. private:
  177. HttpRequestMethod mMethod;
  178. std::string mUri;
  179. std::string mSubUri;
  180. std::string mBodyContent;
  181. std::string mContentType;
  182. std::string mHeaderAcceptType;
  183. std::map<std::string, std::string> mQueryPairs;
  184. bool m_withToken;
  185. bool mToValidCert;
  186. uint32_t mTimeoutSecs;
  187. restFul_GetTokenCallBack g_tokenCall;
  188. void InitGetToken(restFul_GetTokenCallBack t_getToken) {
  189. if (t_getToken)
  190. g_tokenCall = t_getToken;
  191. else
  192. g_tokenCall = nullptr;
  193. };
  194. };
  195. struct HttpClientPostTypeRequest : public HttpClientRequestConfig
  196. {
  197. HttpClientPostTypeRequest(const std::string& uri)
  198. :HttpClientRequestConfig(HttpRequestMethod::POST, uri, nullptr) {}
  199. };
  200. struct HttpClientUploadRequest : public HttpClientRequestConfig
  201. {
  202. HttpClientUploadRequest(const std::string& uri)
  203. :HttpClientRequestConfig(HttpRequestMethod::DOWNLOAD, uri, nullptr)
  204. {
  205. }
  206. void ClearPararm() { mParams.clear(); }
  207. void AddParams(const std::string& name, const std::string& value)
  208. {
  209. mParams.push_back(std::move(std::pair<std::string, std::string>(name, value)));
  210. }
  211. void SetDefaultParam(const std::string& value)
  212. {
  213. AddParams("params", value);
  214. }
  215. void ClearFiles() { mFiles.clear(); }
  216. void AddFiles(const std::string& filePath)
  217. {
  218. mFiles.push_back(std::move(std::pair<std::string, std::string>("file_content", filePath)));
  219. }
  220. virtual void PreDo()
  221. {
  222. auto p = BuildBodyContent();
  223. std::cout << p.second << std::endl;
  224. SetBodyContent(p.second, std::string("multipart/form-data; boundary=") + p.first);
  225. }
  226. std::pair<std::string, std::string> BuildBodyContent() const;
  227. private:
  228. std::vector<std::pair<std::string, std::string> > mParams;
  229. std::vector<std::pair<std::string, std::string> > mFiles;
  230. };
  231. struct HttpClientDownloadRequest : public HttpClientRequestConfig
  232. {
  233. HttpClientDownloadRequest(const std::string& uri)
  234. :HttpClientRequestConfig(HttpRequestMethod::DOWNLOAD, uri, nullptr) {
  235. SetAcceptType("*/*");
  236. }
  237. };
  238. class RESTFULFUNC_API RestfulClient
  239. {
  240. public:
  241. static RestfulClient& getInstance(); // Singleton
  242. ~RestfulClient();
  243. void Do(const HttpClientRequestConfig* const pRequestConfig, HttpClientResponseResult* pResponse) const;
  244. private:
  245. RestfulClient();
  246. private:
  247. };
  248. #endif //_OTHER_RESFULFUNCEXPORT_HEADER_