0

I try to send a HTTP (REST) request to a server with cpprestsdk.

void postRestRequest(const std::string& uri, const std::string& requestJson) {
  const std::string host = "localhost:8080";
  const http_client_config authorization = setupAuthorization();

  http_client client(U(host), authorization);
  http_request request(methods::POST);
  uri_builder builder(U(uri));
  request.set_request_uri(builder.to_string());

  if (not requestJson.empty()) {
    const auto mimeType = utf8string("application/json; charset=utf-8");
    request.set_body(requestJson, mimeType); // SEGFAULT here
  }
}

The call stack is:

-|libpthread.so.0
-|[1]
-|
-|libcpprest.so.2.9
-|[2]    : pplx::task_completion_event<unsigned long>::set(unsigned long) const+0xb4
-|
-|mylib.so
-|[3]    : postRestRequest(std::string const&, std::string const&)+0x49a

I'm not sure if I use the library as expected. I don't know exactly how the tasks in the pplx library work.

Could it also be a bug in the cpprestsdk library. But creating HTTP requests is an essential part of a REST framework. So I can't imagine that there is a unknown bug in the librrary.

Linux: RHEL7
cpprestsdk: 2.9
gcc: 6.3.1

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
woodtluk
  • 935
  • 8
  • 20
  • How did you create `requestJson`? You should build a `web::json::value` with your request. Then you parameterize `request.set_body()` with the serialized `web::json::value`. – Wum Feb 15 '18 at 11:26
  • We use a different JSON library. So I provide it as a std::string – woodtluk Feb 15 '18 at 12:49
  • Following the information on https://github.com/Microsoft/cpprestsdk/issues/72 I'd say you need to work with std::wstring. – Wum Feb 15 '18 at 13:13
  • I changed the code to use a `json::value` object instead of a `std::string`: `auto jsonValue = web::json::value::parse(requestJson); request.set_body(jsonValue); // still segfault here` – woodtluk Feb 19 '18 at 08:29
  • Did you check whether the parsing was successful? Does `web::json::value::serialize()` return you something equal to what you put into `web::json::value::parse()`? – Wum Feb 19 '18 at 09:55

2 Answers2

0

This is how I use a web::json::value. Note that I use member functions like value::number to create valid json values for my request object.

web::json::value requestParameters;
requestParameters[U("foo")] = web::json::value::number(1);
requestParameters[U("bar")] = web::json::value::string(U("whatever"));

utility::stringstream_t paramStream;
requestParameters.serialize(paramStream);

web::http::http_request request(web::http::methods::POST);
request.set_request_uri(U("MethodName"));
request.set_body(paramStream.str());
Wum
  • 306
  • 1
  • 10
0

There was a problem how the library was built (as RPM). Now it works.

woodtluk
  • 935
  • 8
  • 20