当 Content-Type 存在时,C libcurl 返回 null Content-Type。

标签 c curl libcurl command-line-interface

我正在尝试使用以下函数查询给定网页的内容类型:

#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>


unsigned int download_doc(const char *url) {
    CURL *curl;
    CURLcode res;
    char *content_type = (char *)malloc(sizeof(char) * 100);

    curl = curl_easy_init();
    if (curl) {
        fout = fopen(fout_name, "w+");
        if (fout == 0) {
            printf("Error(%d): %s\n", errno, strerror(errno));
            exit(EXIT_FAILURE);
        }

        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0L);

        res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &content_type);
        if (CURLE_OK != res) {
            printf("Error(%d): %s\n", res, curl_easy_strerror(res));
            exit(EXIT_FAILURE);
        }
        printf("Content-Type: %s\n", content_type);

        curl_easy_cleanup(curl);
    }
    return 1;
}

int main() {
    download_doc("http://google.com");
}

上面的代码打印出Content-Type: (null),从文档来看这似乎意味着协议(protocol)不支持Content-Type(HTTP支持),或者Content-Type标题中没有给出。但是,CLI 打印出以下内容:

curl -i http://google.com

HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Mon, 21 Apr 2014 08:02:10 GMT   
Expires: Wed, 21 May 2014 08:02:10 GMT
Cache-Control: public, max-age=2592000

Content-Type 是存在的,但是,似乎从 C 代码访问的 libcurl 说没有 Content-Type。

我做错了什么吗?

最佳答案

您需要调用函数

curl_easy_perform(curl);

curl_easy_getinfo之前。

并且也不需要对字符指针content_type进行malloc,因为curl_easy_getinfo将返回指向字符串的指针,因此请在代码中进行如下更改

unsigned int download_doc(const char *url) {
    CURL *curl;
    CURLcode res;

    curl = curl_easy_init();
    if (curl) {
        fout = fopen(fout_name, "w+");
        if (fout == 0) {
            printf("Error(%d): %s\n", errno, strerror(errno));
            exit(EXIT_FAILURE);
        }

        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0L);


        res = curl_easy_perform(curl);

        if(CURLE_OK == res) {
             char *content_type;
            /* ask for the content-type */
            res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &content_type);
            if((CURLE_OK == res) && content_type)
                printf("We received Content-Type: %s\n", content_type);
        }

        curl_easy_cleanup(curl);
    }
    return 1;
}

关于当 Content-Type 存在时,C libcurl 返回 null Content-Type。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23193415/

相关文章:

c - 格式 '%s' 需要类型为 'char *' 的参数,但参数 2 的类型为 'char **'

c - 选择性调用写包装器

c - 如何在 Linux 中将套接字链接到 PID?

git - 通过cURL删除Bitbucket存储库

c++ - 使用 curl 解压 gzip 数据

php - 使用代理和通过代理建立隧道有什么区别

objective-c - Objective-C 或 C 中的线性回归

javascript - 我在这行代码中得到 "Type Error: Cannot read property of undefined"

php - file_get_contents 同步或异步

c++ - 当服务器无法访问时,curl_easy_perform 返回 -1