Boost.Asio-使用Boost.Asio和OpenWeatherMap API获取天气的简单示例

OpenWeatherMap API是一个提供天气数据的开放接口,可以通过该接口获取全球范围内的实时天气。
1.获取OpenWeatherMap API的密钥
去官网https://openweathermap.org注册后,自主生成密钥,如图

Boost.Asio-使用Boost.Asio和OpenWeatherMap API获取天气的简单示例_第1张图片

2.获取用的代码

#include "stdafx.h"
#include 
#include 
#include 
#include 

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;
}

服务器返回内容如下(原始字符串):
Boost.Asio-使用Boost.Asio和OpenWeatherMap API获取天气的简单示例_第2张图片
3.Boost.Asio-使用Boost.Asio和OpenWeatherMap API获取天气的简单示例_第3张图片

你可能感兴趣的:(Boost.Asio)