How to POST using cpprest-sdk without using any json data

280 Views Asked by At

I'm new to the REST API world and to the cpprest-sdk. I have a curl call that I want to convert to a program using cpprest-sdk. Here is my curl call:

curl -X POST "https://my.url/api/v1/APIKey/GetToken" -H "accept: */*" -H "X-API-KEY: v3geE359Qp7f" -d "{}"

And here is the output of the curl call:

{"Data":{"token":"eyJhbGciOiXVAzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6Ijg3ODIyMzUiLCJUVEwiOiIxNzk5OTk5Ljk5MDQiLCJleHAiOjE2MDcwMjI2MDIsImlzcyI6IlZlbG9jaXR5X2RlbW8iLCJhdWQiOiJFeHRBcGkifQ.h5W5NNTaUKs5qMn7RblY616svitNEHdqkqnFQP50Im4","ttl":1799999.9904,"expires":1607022602588.6367},"Success":true,"Message":"Ok"}

I want to get the value of the "token" field on the return of the POST. All the examples that I have found all use JSON data in their request. As you can see from the curl call, there is no JSON data to be sent.

I have tried doing the following but it returns: Error exception:POST Returned 405

There are so many different types of calls to http_client.request() and I don't even know if I'm using the correct one. Any help would be greatly appreciated.

#include <iostream>
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>

using namespace utility;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace web::http::details;
using namespace concurrency::streams;

int main(int argc, char* argv[])
{
    if (argc < 4)
    {
            printf("Usage: %s <report_name> <from_date> <to_date>\n", argv[0]);
            return 0;
    }

    auto postToken = pplx::create_task([]() {
            uri_builder builder(U("/api"));
            builder.append_path(U("v1"));
            builder.append_path(U("APIKey"));
            builder.append_path(U("GetToken"));

            http_request req(methods::POST);
            req.headers().add(U("accept"), U("*/*"));
            req.headers().add(U("X-API-KEY"), U("v3geE359Qp7f"));
            return http_client(U("https://my.url"))
            .request(req);
    })
    .then([](http_response response) {
                    if (response.status_code() != 201) {
                            throw std::runtime_error("POST Returned " + std::to_string(response.status_code()));
                    }
                    printf("Received response status code: %u\n", response.status_code());

                    return response.extract_json();
    })
    .then([](json::value jsonObject) {
                    return jsonObject[U("Data")];
    })
    .then([](json::value jsonObject) {
                    std::cout << jsonObject[U("token")].as_string() << std::endl;
    });

    try {
            postToken.wait();
    }
    catch (const std::exception &e) {
            printf("Error exception:%s\n", e.what());
    }
}
0

There are 0 best solutions below