libcurl未初始化的变量卷曲错误

时间:2016-05-09 09:37:23

标签: c++ json libcurl

我正在尝试创建一个HTTP请求来检索一些JSON数据;我得到的错误是curl变量没有初始化,虽然我easy_init()它。如何解决这个错误的任何帮助都会非常友好!!

以下是我的代码:

#pragma once
#include "stdafx.h"
#include "RequestJson.h"
#include <string.h>
#include <include/curl/curl.h>
#include <fstream>
#include <iostream>
#include <sstream> 


using namespace std;
class RequestJson
{
public:

    static std::string RequestJsonString(std::string URL)
    {
        //set to get the JSON Response on listed loans; open a CSV file and read unemployment and other indices.

        ::CURL *curl;
        CURLcode res;
        struct curl_slist *headers = NULL;
        std::ostringstream oss;

        //curl_global_init(CURL_GLOBAL_ALL);
        curl = curl_easy_init();
        curl_slist_append(headers, "Accept: application/json");
        curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_cleanup(curl);        

        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_HTTPHEADER, headers);
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer); //define a write-function below. 
            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;
                    }
            }
        }
    }

    //parse the JSON String and return the downloaded string. 
    static std::string *DownloadedResponse;
    static int writer(char *data, size_t size, size_t nmemb, std::string *buffer_in)
    {
        if (buffer_in != NULL)
        {
            buffer_in->append(data, size * nmemb);
            DownloadedResponse = buffer_in;
            return size * nmemb;
        }

        return 0;
    }


};

1 个答案:

答案 0 :(得分:0)

来自the curl_easy_cleanup reference

  

此功能必须是最后一个功能才能调用简单的会话。它与curl_easy_init函数相反,必须使用与curl_easy_init调用返回的输入相同的句柄调用。

[强调我的]

当您致电curl_easy_cleanup时,会清理 curl_easy_init分配的所有资源。之后,您无法再使用CURL指针。

正如参考文献所述:当你完成时,将它最后