如何从 C++ 程序中的网站获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4488128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I fetch data from a website inside a C++ program
提问by Ben313
I want to write a program in C++ that helps to manage my hockey pool, and one of the key things i will need to do is read off the schedule for the week ahead. I was hoping to use the NHL website. is there any way to have the program download the HTML file for a given url, and then parse that? i suppose that once i have the file downloaded, Simple file I/O would do, but im not sure how to download the file.
我想用 C++ 编写一个程序来帮助管理我的曲棍球池,我需要做的关键事情之一就是阅读下一周的日程安排。我希望使用 NHL 网站。有没有办法让程序下载给定 url 的 HTML 文件,然后解析它?我想一旦我下载了文件,简单的文件 I/O 就可以了,但我不确定如何下载文件。
回答by Palmik
I would use some library providing Http abstraction.
我会使用一些提供 Http 抽象的库。
For example:
例如:
#include <boost/network/protocol/http/client.hpp>
#include <string>
#include <iostream>
int main()
{
boost::network::http::client client;
boost::network::http::client::request request("http://www.example.com");
request << boost::network::header("Connection", "close");
boost::network::http::client::response response = client.get(request);
std::cout << body(response);
}
I do not think it can get much easier than that
我认为没有比这更容易的了
On GNU/Linux compile with:
在 GNU/Linux 上编译:
g++ -I. -I$BOOST_ROOT -L$BOOST_ROOT/stage/lib -lboost_system -pthread my_main.cpp
Example for this could get quite long, since QHttp can send only non-blocking requests (that means, that you have to catch some signals reporting that the request was finished, etc.). But the documentation is superb, so it should not be a problem. :)
这个例子可能会很长,因为 QHttp 只能发送非阻塞请求(这意味着你必须捕捉一些报告请求已完成的信号,等等)。但是文档很棒,所以应该不会有问题。:)
回答by darioo
回答by user1638291
I finally managed to compile it and link with:
我终于设法编译它并链接到:
g++ -I. -I/usr/include -lboost_thread -lboost_system
-lcppnetlib-client-connections -lcppnetlib-server-parsers
-lcppnetlib-uri -pthread main.cpp