如何发出包含基本身份验证标头和JSON正文的POST请求?

时间:2017-04-04 02:22:41

标签: c++ json rest cpprest-sdk

我正在尝试使用CPPRESTSDK(a.k.a. Casablanca)将数据发送到RESTful服务器。为此,我创建了一个请求,并指定了一个标题:

// create request, and add header information
web::http::http_request req(methods::POST);
req.headers().add(header_names::authorization, authStr); // authStr is base64 representation of username & password
req.headers().add(header_names::content_type, http::details::mime_types::application_json);

接下来,我创建一个包含所有键值对的web :: json :: value对象:

web::json::value obj = json::value::object();
obj[U("Key1")] = web::json::value::string(U("Val1")];
obj[U("Key2")] = web::json::value::string(U("Val2")];
obj[U("Key3")] = web::json::value::string(U("Val3")];

然后我通过调用:

将此对象存储在请求的正文中
req.set_body(obj);

最后,我使用http_client发送请求到服务器:

// create http client
web::http::client::http_client client(addr); // addr is wstring

return client.request(req).then([](http_response response) {
    return response;
});

问题是这没有做任何事情。如果我在这一行放置一个断点,我会得到有关“400 Bad Request”的信息。我会假设请求的正文有点格式错误,但也可能是我错过了标题中的一些信息。当我在同一个URL上发出GET请求时,不会发生此错误,因此它绝对是POST的问题。你觉得怎么样?

这是一个有效的例子:

// create a new channel
pplx::task<web::http::http_response> postChannel(http_client client, std::wstring authStr, std::wstring cDesc, std::wstring cName, std::string cDiagCap, int cNormFloat, int cWriteDuty,
int cWriteMeth, std::string cItemPersist, std::wstring cItemPersistDat) {
// create request
http_request req(methods::POST);
req.headers().add(header_names::authorization, authStr);

std::wstring url = L"/config/v1/project/channels";
req.set_request_uri(url);

json::value obj = json::value::object();
obj[U("common.ALLTYPES_DESCRIPTION")] = json::value::string(cDesc);
obj[U("common.ALLTYPES_NAME")] = json::value::string(cName);
obj[U("servermain.CHANNEL_DIAGNOSTICS_CAPTURE")] = json::value(cDiagCap == "true" || cDiagCap == "t");
obj[U("servermain.CHANNEL_NON_NORMALIZED_FLOATING_POINT_HANDLING")] = json::value(cNormFloat);
obj[U("servermain.CHANNEL_WRITE_OPTIMIZATIONS_DUTY_CYCLE")] = json::value(cWriteDuty);
obj[U("servermain.CHANNEL_WRITE_OPTIMIZATIONS_METHOD")] = json::value(cWriteMeth);
obj[U("servermain.MULTIPLE_TYPES_DEVICE_DRIVER")] = json::value::string(U("Simulator")); // right now, Simulator channels are the only option
obj[U("simulator.CHANNEL_ITEM_PERSISTENCE")] = json::value(cItemPersist == "true" || cItemPersist == "t");
obj[U("simulator.CHANNEL_ITEM_PERSISTENCE_DATA_FILE")] = json::value::string(cItemPersistDat);

req.set_body(obj);

return client.request(req).then([](http_response response) {
    return response;
});

}

0 个答案:

没有答案