[SOLVED] Using juce::URL to send POST with body

Hi, I’m trying to send data in an HTTP POST, where the data is not stored in parameters but in the body (form-data). A simple Postman request which works looks like this:

image

Or as a curl command:

curl --location 'http://myServer.com/do_something' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'instrument=piano'

I’ve tried to replicate this with the juce::URL class without success so far:

	juce::URL url = juce::URL ("http://myserver.com/do_something");

	juce::DynamicObject* dyn_obj = new juce::DynamicObject;
	dyn_obj->setProperty ("instrument", "piano");
	url = url.withPOSTData (JSON::toString (juce::var (dyn_obj)));

	// using juce URL parameters feature doesn't work either:
	// url = url.withParameter ("instrument", "piano");

	auto options = juce::URL::InputStreamOptions (juce::URL::ParameterHandling::inPostData)
	                   .withExtraHeaders ({"Content-Type: application/x-www-form-urlencoded"})
	                   .withConnectionTimeoutMs (10000)
	                   .withResponseHeaders (&response_headers)
	                   .withStatusCode (&status_code)
	                   .withNumRedirectsToFollow (5)
	                   .withHttpRequestCmd ("POST");

	std::unique_ptr<InputStream> stream (url.createInputStream (options));

Now upon firing this, the server returns that the body field instrument is missing. My best guess is that the post data I appended to the request is not in fact stored in the body, but in the parameters.

Is there a way to tell the URL class to embed the information correctly?

I found a solution. To anyone wondering in the future, the problem was that the line

url = url.withPOSTData (JSON::toString (juce::var (dyn_obj)));

Would generate the data in json form like so:

{
  "instrument": "piano"
}

However, what was needed in this case apparently is simply

url = url.withPOSTData ("instrument=piano");