libcurl未初始化变量curl错误

libcurl uninitialized variable curl error

本文关键字:curl 错误 变量 初始化 libcurl      更新时间:2023-10-16

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

以下是我的代码:

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

};

来自curl_easy_cleanup参考:

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

[强调矿]

当您调用curl_easy_cleanup时,会清理curl_easy_init分配的所有资源。之后就不能再使用CURL指针了。

正如参考资料所说:当你完成时,把它放在最后。