libcurl curl_easy_setopt"未知错误"

时间:2014-06-27 10:36:24

标签: c++ c curl libcurl

我正在尝试使用C ++ cURL库通过PUT方法发送Json数据,我的代码看起来像这样

CURL*    m_curlHandle;
CURLcode m_returnValue;

//function1 start
curl_global_init(CURL_GLOBAL_ALL);

struct curl_slist* headers = NULL;
std::ostringstream oss;
struct curl_slist* slist = NULL;
slist = curl_slist_append(headers, "Accept: application/json");
slist = curl_slist_append(headers, "Content-Type: application/json");
slist = curl_slist_append(headers, "charsets: utf-8");

m_curlHandle = curl_easy_init();

if (!m_curlHandle)
    // throw exception

curl_easy_setopt(m_curlHandle, CURLOPT_HTTPHEADER, headers);
//function1 end

//function2 start
std::string url = "some URL"; // my url
curl_easy_setopt(m_curlHandle, CURLOPT_URL, url.c_str());
unsigned int timeout = 5;
curl_easy_setopt(m_curlHandle, CURLOPT_TIMEOUT, timeout);
std::string localIp = "some IP"; // my IP address
curl_easy_setopt(m_curlHandle, CURLOPT_INTERFACE, localIp.c_str());
curl_easy_setopt(m_curlHandle, CURLOPT_CUSTOMREQUEST, "PUT");
std::string json = "some json struct"; //my json struct
curl_easy_setopt(m_curlHandle, CURLOPT_POSTFIELDS, json.c_str());
curl_easy_setopt(m_curlHandle, CURLOPT_WRITEFUNCTION, callbackWriter); //static size_t callbackWriter(char* buffer, size_t size, size_t nmemb, void* userp);
m_returnValue = curl_easy_perform(m_curlHandle);
//function2 end

我调用function1然后调用function2,问题是对于所有curl_easy_setopt调用,我得到错误代码1685083487和错误描述“未知错误”。那么可能导致这样的结果以及如何解决这个问题呢?

提前谢谢!

1 个答案:

答案 0 :(得分:0)

我会改用CURLOPT_POSTFIELDS,我的func就是这样的

void poolStr(const std::vector<unsigned char> &data, const std::string &url)
{
curl_global_init(CURL_GLOBAL_DEFAULT);
mCurl = curl_easy_init();
if(mCurl) 
{

        curl_easy_setopt(mCurl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(mCurl, CURLOPT_POST, 1L);
        curl_easy_setopt(mCurl, CURLOPT_POSTFIELDSIZE, data.size());
        curl_easy_setopt(mCurl, CURLOPT_POSTFIELDS, &data[0]);
        mChunk = curl_slist_append(mChunk, "Content-Type: application/binary");
        mChunk = curl_slist_append(mChunk, "Expect:");
        curl_easy_setopt(mCurl, CURLOPT_HTTPHEADER, mChunk);

        CURLcode res = curl_easy_perform(mCurl);
        if(res != CURLE_OK)
        {
            LOGERROR << "curl_easy_perform() failed: " << curl_easy_strerror(res) << "\n Attepmt number: " << attempt;
        }
        else
        {
            LOGINFO << "Data being sent.";
        }
    }
}
}

并调用类似poolStr(data,mHost);