Libcurl错误将接收的数据写入磁盘/应用程序失败

时间:2017-09-01 18:16:04

标签: c++ oop libcurl

我正在编写一个类来使用libcurl2创建一个简单的http get请求。 我收回了以下错误:

  

Libcurl错误将收到的数据写入磁盘/应用程序失败

我是C ++的新手,还在学习,但我猜它与Access Modifiers或范围有关

我希望有人可以帮我解决这个问题。

类HTTP连接

#include "HTTPconnection.h"
#include <iostream>
#include <string>

using namespace httptest;

HTTPconnection::HTTPconnection()
{
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
}

size_t HTTPconnection::write_callback(char * data, size_t 
size, size_t nmemb, std::string * writerData)
{
    if (writerData == NULL)
        return 0;

    writerData->append(data, size*nmemb);
    return size * nmemb;
}

std::string HTTPconnection::createConnection(const char *url, const char *proxy)
{
    curl_easy_setopt(HTTPconnection::curl, CURLOPT_URL, url);

    curl_easy_setopt(HTTPconnection::curl, CURLOPT_WRITEFUNCTION, &HTTPconnection::write_callback);
    curl_easy_setopt(HTTPconnection::curl, CURLOPT_WRITEDATA, &HTTPconnection::buffer);

    res = curl_easy_perform(HTTPconnection::curl);
    std::cout << curl_easy_strerror(res);

    return buffer;
}


HTTPconnection::~HTTPconnection()
{
    curl_easy_cleanup(curl);
    curl_global_cleanup();
}

HTTPconnection.h

#ifndef HTTPconnection_H
#define HTTPconnection_H

#include <string>
#include "libcurl/include/curl/curl.h"

#ifdef _DEBUG
#pragma comment(lib, "libcurl/lib/libcurl_a_debug.lib")
#else
#pragma comment(lib, "libcurl/lib/libcurl_a.lib")
#endif


namespace httptest
{
    class HTTPconnection
    {
    public:
        //Default Constructor
        HTTPconnection();
        std::string createConnection(const char *url, const char *proxy);

        //Destructor
        ~HTTPconnection();

    private:

        //methods
        size_t write_callback(char *data, size_t size, size_t nmemb, std::string *writerData);

        //members
        std::string buffer;
        CURL *curl;
        CURLcode res;

    };
}

#endif // !HTTPconnection_H 

2 个答案:

答案 0 :(得分:2)

从curllib API调用中获得的错误表明在保存接收的数据期间发生了问题。

由于你设置了回调卷曲认为回调失败了。

Curl将假设回调未能处理接收到的数据,返回的值与接收的字节数不同。

在您的情况下,这意味着您已使用return 0;进入分支 - 您应该可以通过在回调中设置断点来调试它。

在回调的最后一个参数中收到nullptr的原因 - 你已经将它声明为类的非静态成员,这意味着它隐藏了第一个参数,调用此回调的C代码不知道。

您的案例中的解决方案应该很简单 - 将write_callback声明为静态(或自由)函数。在其中设置断点并查看curl提供的所有参数都是有效的。您可能需要更改回调调用约定以匹配curllib预期的函数签名。

答案 1 :(得分:0)

回调函数需要返回 size_t 对象:

static size_t write_data(char *ptr, size_t size, size_t nmemb, void *user){

    // If you're expecting JSON as response: parse pointer
    nlohmann::json res = nlohmann::json::parse(ptr);
    // print JSON
    std::cout << res.dump();

    return size * nmemb;
}

更多信息herehere