C++ rest sdk POST form data json

Máté Eke picture Máté Eke · Oct 3, 2015 · Viewed 10.3k times · Source

Is it possible to post "form data" whith C++ rest SDK (Casablanca)? I have a given web service which looking for post data in "form data", not in the body.

This is the C++ code:

http_client client(L"http://localhost/posttest/jsontest.php");

// Manually build up an HTTP request with header and request URI.
http_request request(methods::POST);
request.headers().add(L"Content-Type", L"application/json");
request.headers().add(L"Content-Length", L"100");
request.headers().add(L"Host", L"example.com");
request.headers().add(L"X-Requested-With", L"XMLHttpRequest");
request.set_body(obj);
return client.request(request).then([id](http_response response)
{
    if (response.status_code() == status_codes::OK)
    {
        return response.extract_json();
    }
    else {
        /* Print bad status code */
        wcout << L"Server returned returned status code " << response.status_code() << L'.' << std::endl;
    }
    return pplx::task_from_result(json::value());
})

The web service can only use data like this (I can't modify it):

$arr = [$_POST['code']];
header('Content-Type: application/json');
echo json_encode($arr);

(This is just a sample PHP code, what I use for testing)

Answer

M&#225;t&#233; Eke picture Máté Eke · Oct 5, 2015

That is the way:

utility::string_t Lreq = L"code=" + Lcode;

http_client client(L"http://localhost/posttest/jsontest.php");

// Manually build up an HTTP request with header and request URI.

http_request request(methods::POST);
request.headers().add(L"Content-Type", L"application/x-www-form-urlencoded; charset=UTF-8");
request.headers().add(L"Content-Length", L"100");
request.headers().add(L"Host", L"testhost.com");
request.headers().add(L"X-Requested-With", L"XMLHttpRequest");
request.set_body(Lreq);