为什么libcurl返回" 0"在JSON响应字符串之后?

时间:2017-05-11 00:33:54

标签: c++ json libcurl

我试图将图片上传到imgur API。我尝试使用postman REST客户端,它会返回我想要的内容。当我在C ++中使用libcurl时,它会返回:

{"data":{"id":"NsmDwZN","title":null,"description":null,"datetime":1494462656,"type":"image\/png","animated":false,"width":28,"height":22,"size":336,"views":0,"bandwidth":0,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":0,"is_ad":false,"in_most_viral":false,"tags":[],"in_gallery":false,"deletehash":"...","name":"","link":"..."},"success":true,"status":200}
0

0来自哪里?

这是我的主要POST代码:

int postToImgur(std::string file)
{
    curl_global_cleanup();

    CURL *curl;
    CURLcode res;

    // Init winsock stuff
    curl_global_init(CURL_GLOBAL_ALL);

    // Get curl handle
    curl = curl_easy_init();

    struct curl_httppost *formpost = NULL;
    struct curl_httppost *lastptr = NULL;
    struct curl_slist *headerlist = NULL;

    if (curl) {
        curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "image", CURLFORM_FILE, file.c_str(), CURLFORM_END);
        headerlist = curl_slist_append(headerlist, "Expect:");
        headerlist = curl_slist_append(headerlist, "Authorization: Client-ID bea02xxxxxaf4");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
        curl_easy_setopt(curl, CURLOPT_URL, "https://api.imgur.com/3/image");
        curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

        res = curl_easy_perform(curl);

        if (res != CURLE_OK) {
            MessageBox(NULL, _T("Could not upload image. Please check your internet connection."), _T("Error"), NULL);
        }

        curl_easy_cleanup(curl);
        curl_formfree(formpost);
        curl_slist_free_all(headerlist);
    }
    return 0;
}

在我的write_callback函数中,我只是这样做:

size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
CStringA responseStringA(ptr);
OutputDebugStringA((LPCSTR) responseStringA);

它输出" 0"。这打破了我的解析,我不得不手动删除0,但似乎有点草图必须这样做。关于我从哪里得到这个0的任何建议?

1 个答案:

答案 0 :(得分:0)

感谢戴的帮助。 Libcurl不会将响应中的ptr作为以null结尾的char数组传递。这就是我的错误来自的地方。我想我有一个工作的解决方案来创建另一个(更大的)char数组,复制前一个,然后将最后一个字符设置为空终止符号。

请检查我的解决方案并让我知道我是否会以某种方式搞乱:

size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{

    char * responseString = new char[nmemb + 1]();
    strncpy(responseString, ptr, nmemb);
    responseString[nmemb] = '\0';
    OutputDebugStringA(responseString);
    ...
}