Как получить дату и время из интернета?
Нужно получить дату и время из интернета. Для моей программы, ибо если брать дату с компьютера, то пользователь может ее поменять и обмануть программу. Я новичок в с++ и по этому не знаю как это сделать. Я загуглил что это как то можно сделать с TIdSNTP, но как это подключить у себя в проекте я так и не нашел.
Ответы (1 шт):
Вот пример получения московского времени в формате UNIX через сервис http://worldtimeapi.org/ с помощью библиотеки cpprestsdk
#include <cpprest/http_client.h>
#include <cpprest/json.h>
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
int main(int argc, char* argv[])
{
// Make a GET request.
auto requestJson = http_client(U("http://worldtimeapi.org"))
.request(methods::GET,
uri_builder(U("api/timezone/Europe/Moscow")).to_string())
// Get the response.
.then([](http_response response) {
// Check the status code.
if (response.status_code() != 200) {
throw std::runtime_error("Returned " + std::to_string(response.status_code()));
}
// Convert the response body to JSON object.
return response.extract_json();
})
.then([](json::value jsonObject) {
return jsonObject[U("unixtime")];
})
.then([](json::value jsonObject) {
std::cout << jsonObject.as_integer() << std::endl;
});
// Wait for the concurrent tasks to finish.
try {
requestJson.wait();
}
catch (const std::exception& e) {
printf("Error exception:%s\n", e.what());
}
return 0;
}
Заметьте, что стабильность работы сервиса не гарантируется.
Can I use it for commercial applications?
It is not recommended that this API be used for commercial applications. The API can go down from time-to-time, for relatively long periods. It is provided with no SLA, no guarantees, and no direct funding.
Using this API for commercial applications is done entirely at your own risk. Development is ongoing, changes are made frequently, and there is no guarantee of stability or uptime.
The project is entirely funded at a loss, and should costs become prohibitive the API will, with a heavy heart, be taken down permanently.
If you require a stable platform with guaranteed uptime, we are happy to discuss provision of dedicated solutions for a monthly fee. Please contact us for more details.
We would also like to ask users of this API to please consider contributing via a regular donation to help cover hosting costs and to keep this project alive.