mirror of
https://gitlab.com/comunic/comunicterm
synced 2024-11-16 10:31:06 +00:00
56 lines
1.4 KiB
C++
56 lines
1.4 KiB
C++
#include <cpprest/http_client.h>
|
|
#include <cpprest/json.h>
|
|
|
|
#include <helpers/accounthelper.h>
|
|
|
|
#include "api_request.h"
|
|
#include "config.h"
|
|
|
|
using namespace std;
|
|
using namespace web;
|
|
using namespace web::http;
|
|
using namespace web::json;
|
|
|
|
ApiRequest::ApiRequest(const std::string &uri, bool needLogin)
|
|
: mURI(uri)
|
|
{
|
|
this->addArg("serviceName", API_CLIENT_NAME);
|
|
this->addArg("serviceToken", API_CLIENT_TOKEN);
|
|
|
|
if(needLogin) {
|
|
const auto tokens = AccountHelper::loginTokens();
|
|
this->addArg("userToken1", tokens[0]);
|
|
this->addArg("userToken2", tokens[1]);
|
|
}
|
|
}
|
|
|
|
void ApiRequest::addArg(const std::string &name, const std::string &value)
|
|
{
|
|
if(mReqBody.length() > 0)
|
|
mReqBody += "&";
|
|
|
|
mReqBody += uri::encode_data_string(name) + "=" + uri::encode_data_string(value);
|
|
}
|
|
|
|
ApiResponse ApiRequest::exec()
|
|
{
|
|
try {
|
|
http_request req(methods::POST);
|
|
req.headers().add("Content-Type", "application/x-www-form-urlencoded");
|
|
req.set_body(this->mReqBody);
|
|
|
|
|
|
web::http::client::http_client c(API_URL + this->mURI);
|
|
auto task = c.request(req);
|
|
|
|
task.wait();
|
|
auto res = task.get();
|
|
|
|
return ApiResponse(res.status_code(), res.extract_json().get());
|
|
|
|
} catch(exception &e) {
|
|
cerr << "Error on request!" << e.what() << endl;
|
|
return ApiResponse(-1, web::json::value(e.what()));
|
|
}
|
|
}
|