| 84 | |
| 85 | |
| 86 | json_t* requestJson(Method method, const std::string& url, json_t* dataJ, const CookieMap& cookies) { |
| 87 | std::string urlS = url; |
| 88 | CURL* curl = createCurl(); |
| 89 | char* reqStr = NULL; |
| 90 | |
| 91 | // Process data |
| 92 | if (dataJ) { |
| 93 | if (method == METHOD_GET) { |
| 94 | // Append ?key1=value1&key2=value2&... to url |
| 95 | urlS += "?"; |
| 96 | bool isFirst = true; |
| 97 | const char* key; |
| 98 | json_t* value; |
| 99 | json_object_foreach(dataJ, key, value) { |
| 100 | if (json_is_string(value)) { |
| 101 | if (!isFirst) |
| 102 | urlS += "&"; |
| 103 | urlS += key; |
| 104 | urlS += "="; |
| 105 | const char* str = json_string_value(value); |
| 106 | size_t len = json_string_length(value); |
| 107 | char* escapedStr = curl_easy_escape(curl, str, len); |
| 108 | urlS += escapedStr; |
| 109 | curl_free(escapedStr); |
| 110 | isFirst = false; |
| 111 | } |
| 112 | } |
| 113 | } |
| 114 | else { |
| 115 | reqStr = json_dumps(dataJ, 0); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | curl_easy_setopt(curl, CURLOPT_URL, urlS.c_str()); |
| 120 | |
| 121 | // Set HTTP method |
| 122 | if (method == METHOD_GET) { |
| 123 | // This is CURL's default |
| 124 | } |
| 125 | else if (method == METHOD_POST) { |
| 126 | curl_easy_setopt(curl, CURLOPT_POST, true); |
| 127 | } |
| 128 | else if (method == METHOD_PUT) { |
| 129 | curl_easy_setopt(curl, CURLOPT_UPLOAD, true); |
| 130 | } |
| 131 | else if (method == METHOD_DELETE) { |
| 132 | curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE"); |
| 133 | } |
| 134 | |
| 135 | // Set headers |
| 136 | struct curl_slist* headers = NULL; |
| 137 | headers = curl_slist_append(headers, "Accept: application/json"); |
| 138 | headers = curl_slist_append(headers, "Content-Type: application/json"); |
| 139 | curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); |
| 140 | |
| 141 | // Cookies |
| 142 | if (!cookies.empty()) { |
| 143 | curl_easy_setopt(curl, CURLOPT_COOKIE, getCookieString(cookies).c_str()); |
no test coverage detected