使用Libcurl C 从Twitter下载图像

Downloading an image from twitter with libcurl C++

本文关键字:下载 图像 Twitter Libcurl 使用      更新时间:2023-10-16

我正在制作一个获取一个人的推文的程序,如果包含图像,请下载它。

为什么我可以从此URL下载图像(示例#1)
http://www.google.co.id/intl/en_com/images/logo_plain.png
而不是来自此URL(示例#2)
https://www.google.com/imgres?imgurl = https://pbs.twimg.com/media/dr-kkh4xcaaq-vc.jpg&amgrefurl=htttts e

示例#1

#include <iostream> 
#include <curl/curl.h> 
using namespace std;
int main()
{
    CURL *image;
    CURLcode imgresult;
    FILE *fp = nullptr;
    const char *url = "http://www.google.co.id/intl/en_com/images/logo_plain.png";
    image = curl_easy_init();
    if (image)
    {
        // Open file 
        fp = fopen("img.png", "wb");
        if (fp == NULL) cout << "File cannot be opened";
        curl_easy_setopt(image, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(image, CURLOPT_WRITEDATA, fp);
        curl_easy_setopt(image, CURLOPT_URL, url);
        // Grab image 
        imgresult = curl_easy_perform(image);
        if (imgresult)
            cout << "Cannot grab the image!n";
    }
    // Clean up the resources 
    curl_easy_cleanup(image);
    // Close the file 
    fclose(fp);
    system("pause");
    return 0;
}

示例#2

#include <iostream> 
#include <curl/curl.h> 
using namespace std;
int main()
{
    CURL *image;
    CURLcode imgresult;
    FILE *fp = nullptr;
    const char *url = "https://www.google.com/imgres?imgurl=https://pbs.twimg.com/media/DR-kkH4XcAAQ-vc.jpg&imgrefurl=https://twitter.com/officialmcafee/status/945655402276024320&h=1200&w=992&tbnid=0q3B6ZB_UxjRIM&tbnh=247&tbnw=204&usg=__xvjbjSSMvuImESBLVvBBrUagUe8=&docid=vdqkoUmaefYoFM";
    image = curl_easy_init();
    if (image)
    {
        // Open file 
        fp = fopen("img.png", "wb");
        if (fp == NULL) cout << "File cannot be opened";
        curl_easy_setopt(image, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(image, CURLOPT_WRITEDATA, fp);
        curl_easy_setopt(image, CURLOPT_URL, url);
        // Grab image 
        imgresult = curl_easy_perform(image);
        if (imgresult)
            cout << "Cannot grab the image!n";
    }
    // Clean up the resources 
    curl_easy_cleanup(image);
    // Close the file 
    fclose(fp);
    system("pause");
    return 0;
}

首先,这不是图像的链接。这是HTML页面。请注意,您的代码不会下载任何图像 html 页面是指,而只是 html 页面。

第二,您没有关注重定向。再添加一个选项:

curl_easy_setopt(image, CURLOPT_FOLLOWLOCATION, 1);

第三,您最好假装成为浏览器:

curl_easy_setopt(image, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");

添加了两个选项后,我设法下载了您的链接。