【发布时间】:2014-11-07 09:48:59
【问题描述】:
我阅读了教程http://www.vogella.com/tutorials/REST/article.html,我想知道如何在不使用 jerson-client 库的情况下使用 C 或 C++ 从客户端发布和获取 json。非常感谢。
【问题讨论】:
我阅读了教程http://www.vogella.com/tutorials/REST/article.html,我想知道如何在不使用 jerson-client 库的情况下使用 C 或 C++ 从客户端发布和获取 json。非常感谢。
【问题讨论】:
对于 C/C++ 开发,您可以使用 libcurl 库来发出 http 请求。参考[这里]。 http://curl.haxx.se/libcurl/
对于JSON,可以使用jsoncpp。看这里https://github.com/open-source-parsers/jsoncpp
【讨论】:
我有 2 个 C++ Restful 链接
第 1 步:使用 NUGET(名称:casablanca)添加 c++ rest sdk
https://casablanca.codeplex.com/wikipage?title=Using%20NuGet%20to%20add%20the%20C%2b%2b%20REST%20SDK%20to%20a%20VS%20project
第 2 步:Http 客户端教程
http://www.codeproject.com/Articles/603810/Using-Casablanca-to-consume-a-REST-API
在测试此代码之前,您需要更改属于您的主机(http:......)
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include <conio.h>
#include <stdio.h>
#include <string>
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams
//==================GET and save in file abc.txt
auto fileStream = std::make_shared<ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("abc.txt")).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
http_client client(U("http://localhost:8080/JSonJersey/rest"));
// Build request URI and start the request.
uri_builder builder(U("/getEmployee"));
// builder.append_query(U("q"), U("Casablanca CodePlex"));c
return client.request(methods::GET, builder.to_string());
})
// Handle response headers arriving.
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());
// Write response body into the file.
return response.body().read_to_end(fileStream->streambuf());
})
// Close the file stream.
.then([=](size_t)
{
return fileStream->close();
});
// ================POST
pplx::task<int> Post()
{
return pplx::create_task([]
{
json::value postData;
postData[L"id"] = json::value::number(13);
postData[L"firstName"] = json::value::string(L"Baseball");
postData[L"lastName"] = json::value::string(L"hello");
postData[L"age"] = json::value::number(32);
http_client client(L"http://localhost:8080/JSonJersey/rest/class");
return client.request(methods::POST, L"/PostJsonEmployee", postData.to_string().c_str(), L"application/json");
}).then([](http_response response)
{
printf("Received response status code:%u\n", response.status_code());
return 0;
});
}
int main(int argc, char* argv[])
{
// Wait for all the outstanding I/O to complete and handle any exceptions
try
{
requestTask.wait();
Post().wait();
}
catch (const std::exception &e)
{
printf("Error exception:%s\n", e.what());
}
getch();
return 0;
}
【讨论】: