request body support: version with std::string buffer v_0
authorFrantišek Kučera <franta-hg@frantovo.cz>
Tue, 05 Apr 2022 00:18:49 +0200
branchv_0
changeset 26 53c6f76603f6
parent 25 dbeae485a3fd
child 27 b679797949e9
request body support: version with std::string buffer
src/HTTPClient.cpp
--- a/src/HTTPClient.cpp	Tue Apr 05 00:06:12 2022 +0200
+++ b/src/HTTPClient.cpp	Tue Apr 05 00:18:49 2022 +0200
@@ -32,7 +32,7 @@
 public:
 	CURL* curl;
 	char curlErrorBuffer[CURL_ERROR_SIZE];
-	std::stringstream requestBody;
+	std::string requestBody;
 	std::stringstream responseBody;
 	std::stringstream responseHeaders;
 
@@ -94,17 +94,8 @@
 HTTPClient* HTTPClient::open() {
 	HTTPClient::HTTPClientImpl* impl = new HTTPClient::HTTPClientImpl(curl_easy_init());
 
-	typedef size_t(*CurlReadCallback)(char*, size_t, size_t, HTTPClient::HTTPClientImpl*);
 	typedef size_t(*CurlWriteCallback)(char*, size_t, size_t, HTTPClient::HTTPClientImpl*);
 
-	// set request body callback
-	curl_easy_setopt(impl->curl, CURLOPT_READDATA, impl);
-	curl_easy_setopt(impl->curl, CURLOPT_READFUNCTION, (CurlReadCallback)[](char* buffer, size_t size, size_t nmemb, HTTPClient::HTTPClientImpl * impl) {
-		size_t r = size * nmemb;
-		ssize_t bytesRead = impl->requestBody.readsome(buffer, r);
-		return (size_t) bytesRead;
-	});
-
 	// set response body callback
 	curl_easy_setopt(impl->curl, CURLOPT_WRITEDATA, impl);
 	curl_easy_setopt(impl->curl, CURLOPT_WRITEFUNCTION, (CurlWriteCallback)[](char* buffer, size_t size, size_t nmemb, HTTPClient::HTTPClientImpl * impl)->size_t {
@@ -166,11 +157,12 @@
 	for (size_t i = 0; i < request.headers.size(); i += 2) requestHeders.append(request.headers[i] + ": " + request.headers[i + 1]); // TODO: validate, no CR/LF...
 	curl_easy_setopt(impl->curl, CURLOPT_HTTPHEADER, requestHeders.getList());
 
-	// store request body
+	// set request body
 	if (request.body.size()) {
-		impl->requestBody = std::stringstream(request.body);
-		curl_easy_setopt(impl->curl, CURLOPT_UPLOAD, 1L);
-		curl_easy_setopt(impl->curl, CURLOPT_EXPECT_100_TIMEOUT_MS, 0);
+		impl->requestBody = request.body;
+		curl_off_t requestBodySize = impl->requestBody.size();
+		curl_easy_setopt(impl->curl, CURLOPT_POSTFIELDS, impl->requestBody.c_str());
+		curl_easy_setopt(impl->curl, CURLOPT_POSTFIELDSIZE_LARGE, requestBodySize);
 	}