Being a C++ developer ,It was quite difficult to start working with webservices. Believe me after setting a proper development environment it was quite simple to access json webservice and extract json content through VC++.

Setting up environment :

Microsoft provided "C++ Rest SDK" package for accessing json from VC++.
It works with Visual studio 2013/2015 very smoothly.
Use following link to set up "C++ Rest SDK" in your application :

Link

After successfully installation of C++ Rest SDK.
You can use following code to Consume json webservice :

I am giving the simple code example with some webservice that returns json content type.I have developed
it in Visual studio 2015


//The code includes the most frequently used includes necessary to work with C++ REST SDK
#include "stdafx.h"
#include "cpprest/containerstream.h"
#include "cpprest/filestream.h"
#include "cpprest/http_client.h"
#include "cpprest/json.h"
#include "cpprest/producerconsumerstream.h"
#include <iostream>
#include <sstream>
#include <string.h>

using namespace ::pplx;
using namespace utility;
using namespace concurrency::streams;

using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace web::json;
using namespace std;

// Retrieves a JSON value from an HTTP request.
pplx::task<void> RequestJSONValueAsync()
{// TODO: To successfully use this example, you must perform the request
// against a server that provides JSON data. After a long search I have found some webservice on google.

//Declare the http_client
http_client client(L"http://api.geonames.org/citiesJSON\north=44.1\
&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo");

//We are calling GET api of declared http client
return client.request(methods::GET).then([](http_response response) -> pplx::task
{
if (response.status_code() == status_codes::OK)
{
return response.extract_json();
}

// Handle error cases, for now return empty json value...
return pplx::task_from_result(json::value());
})
.then([](pplx::task previousTask)

{
try
{
//You can use either .get/.wait to extract json data
//const json::value& v = previousTask.wait();
const json::value& v = previousTask.get(); // Get json content from result

// Convert json value into string
string_t jsonval = v.serialize(); // convert json value into string

wcout<< jsonval ; //Print extracted json value on console

}
catch (const http_exception& e)
{
// Print error.
wostringstream ss;
ss << e.what() << endl;
wcout << ss.str();
}
});

}

int wmain()
{
// This example uses the task::wait method to ensure that async operations complete before the app exits.
// In most apps, you typically don�t wait for async operations to complete.

cout << L"Calling RequestJSONValueAsync..." << endl;
RequestJSONValueAsync().wait();

}

 

Feel free to ask any doubt on this..

Happy coding !!!

 

Comments