Trouble sending request body with POST request


#1

Hello, I am attempting to send out a POST request to obtain an Oauth2 token from a Django rest api. I’m trying to send a JSON object in the request body to carry the grant type, client credentials and secret with the request. For some reason the request returns a 400 error, and the following: {“error”: “unsupported_grant_type”}. I’ve tried the same request in postman, and it returns a token as expected. Am I doing something wrong here, or is JUCE unable to send JSON as a request body?

URL url = URL("https://url");
StringPairArray responseHeaders;
int statusCode = 0;

DynamicObject* obj = new DynamicObject();
obj->setProperty("grant_type","client_credentials");
obj->setProperty("client_id","id");
obj->setProperty("client_secret","secret");
var json (obj);
String s = JSON::toString(json);

if(!s.isEmpty()) url = url.withPOSTData(s);

std::unique_ptr<InputStream> stream (url.createInputStream (true, nullptr, nullptr, {"Content-Type: application/json"}, 10000, &responseHeaders, &statusCode, 5, "POST"));

String response  = stream->readEntireStreamAsString().toStdString();
String head = responseHeaders.getDescription().toStdString();
if (stream.get() != nullptr){
    std::cout<<"status code: "<<statusCode<<std::endl;
    std::cout<<head<<std::endl;
    std::cout<<response<<std::endl;

#2

The trick to debugging these is to get a dump of a working connection and the a dump of the non-working one with Wireshark https://www.wireshark.org/docs/wsug_html_chunked/ChAdvFollowStreamSection.html

To do this easily you need an unencrypted version of the endpoint (i.e. http not https) which may or may not be possible. And a copy of https://www.getpostman.com/ to easily generate a working request.

You can definitely get this working. We do something similar for Loopcloud.


#3

just curious, why are you using std::cout? why aren’t you using DBG()? all of those std::cout messages will exist in your release build.