* @brief Sends a POST HTTP request to a specified URL * * @param requestInfo Structure containing request data, along with response text * * @return true/false if request was successful * * @usage * bool wasSuccess = HttpClient::PostRequest(requestInfo); */
| 93 | * bool wasSuccess = HttpClient::PostRequest(requestInfo); |
| 94 | */ |
| 95 | bool HttpClient::PostRequest(__inout HttpRequest& requestInfo) |
| 96 | { |
| 97 | bool wasSuccess = false; |
| 98 | CURL* curl = nullptr; |
| 99 | CURLcode res; |
| 100 | |
| 101 | curl_global_init(CURL_GLOBAL_DEFAULT); |
| 102 | curl = curl_easy_init(); |
| 103 | |
| 104 | if (curl) |
| 105 | { |
| 106 | curl_easy_setopt(curl, CURLOPT_URL, requestInfo.url.c_str()); |
| 107 | |
| 108 | curl_easy_setopt(curl, CURLOPT_POST, 1L); |
| 109 | |
| 110 | struct curl_slist* request_headers = NULL; |
| 111 | |
| 112 | if (requestInfo.requestHeaders.size() > 0) |
| 113 | { |
| 114 | for (string header : requestInfo.requestHeaders) |
| 115 | { |
| 116 | request_headers = curl_slist_append(request_headers, header.c_str()); |
| 117 | } |
| 118 | |
| 119 | curl_easy_setopt(curl, CURLOPT_HTTPHEADER, request_headers); //set headers |
| 120 | } |
| 121 | |
| 122 | curl_easy_setopt(curl, CURLOPT_COOKIE, requestInfo.cookie.c_str()); //set cookie |
| 123 | |
| 124 | curl_easy_setopt(curl, CURLOPT_POSTFIELDS, requestInfo.body.c_str()); //set body |
| 125 | |
| 126 | curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L); // Timeout for the whole operation in seconds |
| 127 | curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L); // Timeout for the connection phase in seconds |
| 128 | |
| 129 | curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); // Set the callback function to handle the response data |
| 130 | |
| 131 | curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, HeaderCallback); |
| 132 | curl_easy_setopt(curl, CURLOPT_HEADERDATA, &requestInfo.responseHeaders); |
| 133 | |
| 134 | curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); |
| 135 | |
| 136 | // Set the data pointer |
| 137 | curl_easy_setopt(curl, CURLOPT_READDATA, (void*)0); |
| 138 | |
| 139 | curl_easy_setopt(curl, CURLOPT_WRITEDATA, &requestInfo.responseText); //response data , write to |
| 140 | |
| 141 | res = curl_easy_perform(curl); |
| 142 | |
| 143 | if (res != CURLE_OK) |
| 144 | { |
| 145 | #ifdef LOGGING_ENABLED |
| 146 | Logger::logf(Warning, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); |
| 147 | #endif |
| 148 | goto fail_cleanup; |
| 149 | } |
| 150 | |
| 151 | if (request_headers != nullptr) |
| 152 | curl_slist_free_all(request_headers); |