由 C++ libcurl json rest

标签 c++ json curl libcurl

我正在尝试使用 libcurl 从 C++ 中的 REST 网页下载一个 json 文件。 如果我转到网页,以下代码有效,但如果我尝试访问 json,则它不会下载....

我认为这应该是一个简单的修复,但我找不到任何关于这个的引用......

如果我转到网页,它会打开 json,但此代码仅返回文本/html;字符集=utf-8

??????????

CURL *curl;
CURLcode res;
    struct curl_slist *headers=NULL; // init to NULL is important 
    headers = curl_slist_append(headers, "Accept: application/json");   

curl = curl_easy_init();
if(curl) {

    curl_easy_setopt(curl, CURLOPT_URL, "http://web.com/api/json/123");
            curl_easy_setopt(curl, CURLOPT_HTTPGET,1);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    //curl_easy_setopt(curl, CURLOPT_URL, "http://web.com/123.html");//this works!!!
    res = curl_easy_perform(curl);

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

最佳答案

std::string ServerContent::DownloadJSON(std::string URL)
{   
    CURL *curl;
    CURLcode res;
    struct curl_slist *headers=NULL; // init to NULL is important 
    std::ostringstream oss;
    headers = curl_slist_append(headers, "Accept: application/json");  
    headers = curl_slist_append(headers, "Content-Type: application/json");
    headers = curl_slist_append(headers, "charset: utf-8"); 
    curl = curl_easy_init();

    if (curl) 
    {
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPGET,1); 
        curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,writer);
        res = curl_easy_perform(curl);

        if (CURLE_OK == res) 
        { 
            char *ct;         
            res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
            if((CURLE_OK == res) && ct)
                return *DownloadedResponse;
        }
    }

    curl_slist_free_all(headers);
}


static std::string *DownloadedResponse;

static int writer(char *data, size_t size, size_t nmemb, std::string *buffer_in)
{

    // Is there anything in the buffer?  
    if (buffer_in != NULL)  
    {
        // Append the data to the buffer    
        buffer_in->append(data, size * nmemb);

        // How much did we write?   
        DownloadedResponse = buffer_in;

        return size * nmemb;  
    }

    return 0;

}   

关于由 C++ libcurl json rest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5707957/

相关文章:

c++ - 满足以下条件的高效图算法?

javascript - JSON 到哈希值

android - 如何在 Android 中使用 curl?

c++ - OpenGL 主循环绘制巨大的点 vector

c++ - 检索数据结构对齐信息

c++ - Stroustrup 在定义变量时使用 auto 的原因

mysql - 格式化数据以用于 JSON 和 D3.js

javascript - jQuery 插件 listnav 无法正常使用功能

ssl - 在 Curl 中出现错误 - 无法使用已知的 CA 证书对对等证书进行身份验证

curl - Uber API 不允许来自本地主机的请求