Question

I'm trying to query the content-type of a given web page, using the following function:

#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");
}

The above code prints out Content-Type: (null), which from the documentation seems to mean either the protocol doesn't support Content-Type (HTTP does), or the Content-Type wasn't given in the headers. However, the CLI prints out the following:

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

The Content-Type is there, however, it seems libcurl accessed from C code says there is no Content-Type.

Am I doing something wrong?

Was it helpful?

Solution 2

You forgot to send the request by calling curl_easy_perform(curl) before you called curl_easy_getinfo().

OTHER TIPS

You require to call function

curl_easy_perform(curl);

before curl_easy_getinfo.

And also not require to malloc for char pointer content_type because curl_easy_getinfo will return pointer to string so make changes as follows in your code

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top