RestfulFuncImpl.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. #include "RestfulFunc.h"
  2. #include <cpprest/http_client.h>
  3. using namespace utility; // Common utilities like string conversions
  4. using namespace web; // Common features like URIs.
  5. using namespace web::http; // Common HTTP functionality
  6. using namespace web::http::client; // HTTP client features
  7. RestfulClient& RestfulClient::getInstance()
  8. {
  9. static RestfulClient c;
  10. return c;
  11. }
  12. RestfulClient::RestfulClient()
  13. {
  14. }
  15. RestfulClient::~RestfulClient()
  16. {
  17. }
  18. namespace
  19. {
  20. const http::method MappingHttpRequestMethod(HttpRequestMethod provideMethod)
  21. {
  22. switch (provideMethod) {
  23. case GET:
  24. return http::methods::GET;
  25. break;
  26. case POST:
  27. return http::methods::POST;
  28. break;
  29. case PUT:
  30. return http::methods::PUT;
  31. break;
  32. case DEL:
  33. return http::methods::DEL;
  34. break;
  35. case HEAD:
  36. return http::methods::HEAD;
  37. break;
  38. case OPTIONS:
  39. return http::methods::OPTIONS;
  40. break;
  41. case TRCE:
  42. return http::methods::TRCE;
  43. break;
  44. case CONNECT:
  45. return http::methods::CONNECT;
  46. break;
  47. case MERGE:
  48. return http::methods::MERGE;
  49. break;
  50. case PATCH:
  51. return http::methods::PATCH;
  52. break;
  53. case UPLOAD:
  54. return http::methods::POST;
  55. break;
  56. case DOWNLOAD:
  57. return http::methods::POST;
  58. break;
  59. default:
  60. break;
  61. }
  62. return http::methods::GET;
  63. }
  64. void GetFileNameAndType(const std::string& absoluteFilePath, std::string& fileName, std::string& contentType)
  65. {
  66. size_t pos = absoluteFilePath.find_last_of("/\\");
  67. fileName = absoluteFilePath.substr(pos + 1);
  68. contentType = "application/octet-stream";
  69. pos = fileName.find_last_of(".");
  70. if (pos != std::string::npos) {
  71. std::string ext = fileName.substr(pos + 1);
  72. std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
  73. if (ext == "jpg" || ext == "jpeg") {
  74. contentType = "image/jpeg";
  75. } else if (ext == "txt" /*|| ext == "log"*/) {
  76. contentType = "text/plain";
  77. }
  78. }
  79. }
  80. }
  81. void RestfulClient::Do(const HttpClientRequestConfig* const pRequestConfig, HttpClientResponseResult* pResponse) const
  82. {
  83. http_client_config config;
  84. config.set_validate_certificates(pRequestConfig->NeedValidCert());
  85. const uint32_t timeoutVal = pRequestConfig->GetTimeout();
  86. if (timeoutVal != 0) {
  87. config.set_timeout(utility::seconds(timeoutVal));
  88. }
  89. web::http::client::http_client client(pRequestConfig->GetBaseUri(), config);
  90. http_request request(MappingHttpRequestMethod(pRequestConfig->GetRequestType()));
  91. uri_builder urib(pRequestConfig->GetSubUri());
  92. if (pRequestConfig->GetQueryPairs().size() > 0) {
  93. const auto& queries = pRequestConfig->GetQueryPairs();
  94. for (auto it = queries.cbegin(); it != queries.cend(); ++it) {
  95. urib.append_query(it->first, it->second);
  96. }
  97. }
  98. request.set_request_uri(urib.to_string());
  99. request.headers().add(header_names::accept, pRequestConfig->GetAcceptType());
  100. request.set_body(pRequestConfig->GetBodyContent(), pRequestConfig->GetContentType());
  101. if (pRequestConfig->GetRequestType() == HttpRequestMethod::DOWNLOAD) {
  102. pplx::task<void> requestTask = client.request(request)
  103. .then([pResponse](http_response response) ->pplx::task<std::string> {
  104. pResponse->statusCode = response.status_code();
  105. if (pResponse->ConsiderAsSucc()) {
  106. return response.extract_string();
  107. } else {
  108. std::cout << "response status result: " << response.status_code() << std::endl;
  109. return pplx::task_from_result(std::string());
  110. }
  111. })
  112. .then([pResponse](pplx::task<std::string> vt) {
  113. try {
  114. pResponse->content = vt.get();
  115. } catch (const http_exception& ex) {
  116. pResponse->statusCode = -1;
  117. pResponse->content = ex.what();
  118. }
  119. });
  120. try {
  121. requestTask.wait();
  122. } catch (const std::exception& ex) {
  123. pResponse->statusCode = -1;
  124. pResponse->content = ex.what();
  125. }
  126. } else {
  127. request.set_body(pRequestConfig->GetBodyContent(), pRequestConfig->GetBodyContent());
  128. pplx::task<void> requestTask = client.request(request)
  129. .then([pResponse](http_response response) ->pplx::task<json::value> {
  130. pResponse->statusCode = response.status_code();
  131. if (pResponse->ConsiderAsSucc()) {
  132. return response.extract_json();
  133. } else {
  134. std::cout << "response status result: " << response.status_code() << std::endl;
  135. return pplx::task_from_result(json::value());
  136. }
  137. })
  138. .then([pResponse](pplx::task<json::value> vt) {
  139. try {
  140. json::value const& v = vt.get();
  141. pResponse->content = v.to_string();
  142. } catch (const http_exception& ex) {
  143. pResponse->statusCode = -1;
  144. pResponse->content = ex.what();
  145. }
  146. });
  147. try {
  148. requestTask.wait();
  149. } catch (const std::exception& ex) {
  150. pResponse->statusCode = -1;
  151. pResponse->content = ex.what();
  152. }
  153. }
  154. }
  155. std::pair<std::string, std::string> HttpClientUploadRequest::BuildBodyContent() const
  156. {
  157. std::stringstream data;
  158. std::string boundary{};
  159. for (int i = 0; i < 50; i++) {
  160. boundary += (rand() % 26) + 'A';
  161. }
  162. for (auto& param : mParams) {
  163. data << "\r\n--";
  164. data << boundary;
  165. data << "\r\nContent-Disposition: form-data; name=\"";
  166. data << param.first;
  167. data << "\"\r\n\r\n";
  168. data << param.second;
  169. }
  170. for (auto& file : mFiles) {
  171. std::string inputFileName;
  172. std::string contentType;
  173. GetFileNameAndType(file.second, inputFileName, contentType);
  174. std::ifstream inputFile;
  175. inputFile.open(file.second, std::ios::binary | std::ios::in);
  176. std::string inputFileContent = std::string((std::istreambuf_iterator<char>(inputFile)), (std::istreambuf_iterator<char>()));
  177. data << "\r\n--";
  178. data << boundary;
  179. data << "\r\nContent-Disposition: form-data; name=\"";
  180. data << file.first;
  181. data << "\"; filename=\"";
  182. data << inputFileName;
  183. data << "\"\r\nContent-Type: ";
  184. data << contentType;
  185. data << "\r\n\r\n";
  186. data << inputFileContent;
  187. }
  188. data << "\r\n--";
  189. data << boundary;
  190. data << "--\r\n";
  191. return { boundary, data.str() };
  192. }