1. 풀이 |
간단하게 POST 방식의 api를 활용하며 json 형식의 데이터를 생성해보자.
2. 소스코드 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | #include <iostream> #include <cpprest/http_client.h> #include <cpprest/filestream.h> #include <cpprest/uri.h> #include <cpprest/json.h> #include<cpprest/details/web_utilities.h> //인증 #include<cpprest/oauth2.h> //oauth2 방식의 인증 #include<vector> #include<string> #include<algorithm> using namespace utility; using namespace web; using namespace web::http; using namespace web::http::client; //using namespace concurrency::streams; // json으로 읽어온 body를 파일에 출력할 때 활용 using namespace std; auto POST_request() { // Create user data as JSON object and make POST request. auto postJson = pplx::create_task([]() { json::value jsonObject; jsonObject[U("first_name")] = json::value::string(U("atakan")); jsonObject[U("last_name")] = json::value::string(U("sarioglu")); json::value temp; temp[U("list")] = jsonObject; jsonObject[U("top")] = temp; wcout << jsonObject.serialize() << endl; return http_client(U("https://reqres.in")) .request(methods::POST, uri_builder(U("api")).append_path(U("users")).to_string(), jsonObject.serialize(), U("application/json")); }) // Get the response. .then([](http_response response) { // Check the status code. if (response.status_code() != 201) { throw std::runtime_error("Returned " + std::to_string(response.status_code())); } // Convert the response body to JSON object. return response.extract_json(); }) // Parse the user details. .then([](json::value jsonObject) { std::wcout << "\n==POST request 확인==\n" << jsonObject.serialize() << std::endl; }); return postJson; } int main() { //auto requestJson = GET_request_json(); auto requestJson = POST_request(); // Wait for the concurrent tasks to finish. try { requestJson.wait(); } catch (const std::exception& e) { printf("Error exception:%s\n", e.what()); } return 0; } | cs |
이 부분이 핵심이다.
json::value jsonObject;
jsonObject[U("first_name")] = json::value::string(U("atakan"));
jsonObject[U("last_name")] = json::value::string(U("sarioglu"));
json::value temp;
temp[U("list")] = jsonObject;
jsonObject[U("top")] = temp;
json::value jsonObject이 POST에서 활용하는 query이다.
이 query에서 복잡한 계층이 필요한 경우를 예비해서 미리 테스트를 진행해보았다.
3. 참고 |
질문이나 지적 있으시면 댓글로 남겨주세요~
도움 되셨으면 하트 꾹!
728x90
반응형
'---------개인공부-------- > |c++|' 카테고리의 다른 글
[C++] rest api 활용 (feat. cpprestSDK, boost) (0) | 2020.09.24 |
---|---|
[c++] string to wstring, wstring to string(api 활용을 위한 기초) (0) | 2020.09.24 |
[C++] cpprestSDK (0) | 2020.09.23 |
[c++] 회문(palindrome) (0) | 2019.09.25 |