【发布时间】:2021-04-10 01:56:46
【问题描述】:
*环境 C++ 11 提升 1.73
我关注了https://www.boost.org/doc/libs/1_70_0/libs/beast/doc/html/beast/quick_start/http_client.html的例子。
从自己的Http Server获取数据就成功了(我是说本地127.0.0.1)
但是我无法通过这个例子从谷歌海拔 api 获取数据。
我的“get”函数是。
json HttpClient::GET(std::string host, std::string port, std::string target)
{
njson result = njson::object();
result["state"] = "F";
try{
// The io_context is required for all I/O
net::io_context ioc;
// These objects perform our I/O
tcp::resolver resolver(ioc);
beast::tcp_stream stream(ioc);
// Look up the domain name
auto const results = resolver.resolve(host, port);
// Make the connection on the IP address we get from a lookup
stream.connect(results);
// Set up an HTTP GET request message
http::request<http::string_body> req{http::verb::get, target, HTTP_VERSION };
req.set(http::field::host, host);
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
// Send the HTTP request to the remote host
http::write(stream, req);
// This buffer is used for reading and must be persisted
beast::flat_buffer buffer;
// Declare a container to hold the response
http::response<http::dynamic_body> res;
// Receive the HTTP response
http::read(stream, buffer, res);
// Write the message to standard out
std::string sstr = boost::beast::buffers_to_string(res.body().data());
result = njson::parse(sstr);
// Gracefully close the socket
beast::error_code ec;
stream.socket().shutdown(tcp::socket::shutdown_both, ec);
// not_connected happens sometimes
// so don't bother reporting it.
//
if (ec && ec != beast::errc::not_connected)
throw beast::system_error{ ec };
// If we get here then the connection is closed gracefully
}
catch (std::exception const& e)
{
std::cerr << "Error: " << e.what() << std::endl;
}
return result;
}
这是我的主要内容
// Performs an HTTP GET and prints the response
int main(int argc, char** argv)
{
auto const host = "https://maps.googleapis.com";
auto const port = "443";
auto const target = "/maps/api/elevation/json?locations=39.7391536,-104.9847034&key=MY_KEY";
json res = HttpClient::GET(host,port, target);
std::cout << "***********************" << std::endl;
std::cout << res.dump() << std::endl;
return 0;
}
但结果是。 Resolve: no such host is known
当我编写该代码时,它会执行 catch 语句。
auto const results = resolver.resolve(host, port);
我认为我的一个参数是错误的。但我没有任何想法。 我该怎么办?
【问题讨论】:
标签: c++ boost httpclient resolver