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

时间:2014-04-21 08:06:08

标签: 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),从文档中可能意味着协议不支持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。

我做错了吗?

2 个答案:

答案 0 :(得分:1)

您需要调用函数

curl_easy_perform(curl);
curl_easy_getinfo之前

并且{char}指针malloc也不需要content_type,因为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;
}

答案 1 :(得分:0)

您在致电curl_easy_perform(curl)之前致电curl_easy_getinfo()忘了发送请求。