libcurl访问的链接发生了跳转没有得到指定的html
时间: 2023-07-31 07:05:38 浏览: 51
如果你使用 libcurl 访问的链接发生了跳转(例如 301 或 302),你需要在代码中添加一些额外的设置来跟随重定向。
以下是一个示例代码,它使用 libcurl 访问指定的链接并获取 HTML 内容:
```c++
#include <iostream>
#include <curl/curl.h>
using namespace std;
static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
string *buffer = (string*)userdata;
buffer->append(ptr, size * nmemb);
return size * nmemb;
}
int main()
{
CURL *curl;
CURLcode res;
string buffer;
curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); // 设置跟随重定向
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
}
else
{
cout << buffer << endl; // 输出 HTML 内容
}
curl_easy_cleanup(curl);
}
return 0;
}
```
在以上代码中,`CURLOPT_FOLLOWLOCATION` 参数设置为 1L,表示启用跟随重定向。`write_callback` 是一个回调函数,用于将获取到的数据保存到 `buffer` 中。
如果你的链接需要进行身份验证或者需要添加一些其他的参数,你还需要添加额外的设置。你可以参考 libcurl 的官方文档来获取更多信息:https://curl.se/libcurl/c/
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)