OpenWeatherMap API是一个提供天气数据的开放接口,可以通过该接口获取全球范围内的实时天气。
1.获取OpenWeatherMap API的密钥
去官网https://openweathermap.org注册后,自主生成密钥,如图
2.获取用的代码(方法1)
#include "stdafx.h"
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <algorithm>using boost::asio::ip::tcp;
int main()
{try{boost::asio::io_context io_context;// 创建一个TCP连接tcp::resolver resolver(io_context);tcp::resolver::results_type endpoints = resolver.resolve("api.openweathermap.org", "http");tcp::socket socket(io_context);boost::asio::connect(socket, endpoints);// 发送HTTP请求std::string request = "GET /data/2.5/weather?id=1816670&appid=c7c9b4。。密钥需换成自己的 HTTP/1.1\r\n""Host: api.openweathermap.org\r\n""Connection: close\r\n\r\n";boost::asio::write(socket, boost::asio::buffer(request));// 读取服务器响应boost::asio::streambuf response;boost::asio::read_until(socket, response, "\r\n");// 输出响应结果std::istream response_stream(&response);std::string http_version;response_stream >> http_version;unsigned int status_code;response_stream >> status_code;if (status_code == 200){std::string status_message;std::getline(response_stream, status_message);std::cout << "HTTP/1.1 " << status_code << " " << status_message << std::endl;// 读取并输出天气数据std::cout << &response << std::endl;}else{std::cout << "HTTP request failed with status code: " << status_code << std::endl;}}catch (std::exception& e){std::cout << "Exception: " << e.what() << std::endl;}return 0;
}
2.获取用的代码(方法2)
int main(int argc,char* argv[])
{try{//if (argc != 2)//{// std::cerr << "Usage: daytime_client <host>" << std::endl;// return 1;//}tcp::iostream s("api.openweathermap.org", "http");if (!s){std::cout << "Unable to connect: " << s.error().message() << std::endl;return 1;}s << "GET /data/2.5/weather?q=BeiJing&appid=c7c9b.。。你的密钥 HTTP/1.1\r\n";s << "Host: api.openweathermap.org\r\n";s << "Connection: close\r\n\r\n";// Check that response is OK.std::string http_version;s >> http_version;unsigned int status_code;s >> status_code;std::string status_message;std::getline(s, status_message);if (!s || http_version.substr(0, 5) != "HTTP/"){std::cout << "Invalid response\n";return 1;}if (status_code != 200){std::cout << "Response returned with status code " << status_code << "\n";return 1;}std::cout << http_version << " " << status_code << " " << status_message << std::endl;// Process the response headers, which are terminated by a blank line.std::string header;while (std::getline(s, header) && header != "\r"){ std::cout << header << "\n";}std::cout << "\n";// Write the remaining data to output.std::cout << s.rdbuf();}catch (std::exception& e){std::cout << "Exception: " << e.what() << std::endl;}return 0;
}
服务器返回内容如下(原始字符串):
3.