RestfulFunc.h 8.2 KB

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