我正在尝试将页面的 html 放入一个字符串(或一个 char[])中...(等等)
我知道如何使用基本套接字,并作为客户端/服务器连接...
我过去写过一个客户端,它获取一个 ip 和端口,并连接到它,并使用客户端和服务器之间的套接字发送图像等......
我在网上搜索了一下,发现我可以连接到该网站,并发送一个 GET 请求,以获取页面的 HTTP 内容并将其存储在一个变量中,尽管我遇到了一些问题:
1) 我正在尝试获取不是网站主页的页面的 HTML,例如,不是 stackoverflow.com,而是 stackoverflow.com/help 等(不是“网站的官方页面” ,但该网站内的东西)
2) 我不确定如何发送或存储我从 GET 请求中获得的数据...
我看到我可以使用外部库,但我宁愿只使用套接字...
顺便说一下 - 我正在使用 Windows 7,我的目标是它只能在 Windows 上运行(所以如果它不能在 Linux 上运行也没关系)
感谢您的帮助! :)
要访问某个主机上的资源,您只需在请求的第一行中指定资源的路径,就在“GET”之后。例如。检查http://www.jmarshall.com/easy/http/#http1.1
GET /path/file.html HTTP/1.1
Host: www.host1.com:80
[blank line here]
我还建议使用一些可移植的库,例如 Boost.ASIO,而不是套接字。但我强烈建议您使用一些现有的、可移植的库来实现 HTTP 协议(protocol)。当然,前提是学习如何实现它不是问题。
即使您想自己实现它,了解现有的解决方案也是值得的。例如,这是使用 cpp-netlib ( http://cpp-netlib.org/0.10.1/index.html ) 获取网页的方法:
using namespace boost::network;
using namespace boost::network::http;
client::request request_("http://127.0.0.1:8000/");
request_ << header("Connection", "close");
client client_;
client::response response_ = client_.get(request_);
std::string body_ = body(response_);
这是使用 cURL 库 (http://curl.haxx.se/libcurl/c/simple.html) 的方法:
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
/* example.com is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
这两个库都是可移植的,但如果您想使用某些特定于 Windows 的 API,您可以查看 WinINet ( http://msdn.microsoft.com/en-us/library/windows/desktop/aa383630%28v=vs.85%29.aspx),但使用起来不太愉快。