我正在尝试使用libcurl向服务器发送GET请求并保存响应。当我不使用CURLOPT_WRITEFUNCTION和CURLOPT_WRITEFDATA时,它工作正常,响应转到标准流,按下按钮后程序关闭。
当我添加自己的函数和变量以保存响应时,响应结束时会出现额外的垃圾字符,按下按钮后程序崩溃。
#include <iostream>
#include <tchar.h>
#include <stdio.h>
#include <conio.h>
#include "curl/curl.h"
#include "curl/easy.h"
#define FAIL 0
#define PASS 1
size_t curlWrite(void*, size_t, size_t, void*);
CURL *curl;
const char *baseURL = "XXXX";
const char *authHeader = "Authorization: Token token=YYYY";
int _tmain(int argc, _TCHAR* argv[])
{
bool cURLStatus = PASS;
CURLcode res;
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, authHeader);
char *response;
curl = curl_easy_init();
if(curl)
{
curl_easy_setopt(curl, CURLOPT_URL, baseURL);
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWrite);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, response);
res = curl_easy_perform(curl);
if(CURLE_OK != res) cURLStatus = FAIL;
}
else cURLStatus = FAIL;
if(cURLStatus) printf("Response: %s", response);
else printf("Error: %s", curl_easy_strerror(res));
curl_easy_cleanup(curl);
_getch();
return 0;
}
static size_t curlWrite(void *src, size_t size, size_t nmemb, void *dst)
{
printf("Source: %s", src);
memcpy(dst, src, size * nmemb);
return size * nmemb;
}
这是我得到的回复,然后是APPCRASH,使用上面的代码:
来源:{“current_bac”:0,“time_until_sober”:0}
0
回复:{“current_bac”:0,“time_until_sober”:0} P
如果我注释掉以下行(和printf):
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWrite);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, response);
我明白了:
{ “current_bac”:0 “time_until_sober”:0}
我做错了什么?
答案 0 :(得分:0)
男人,看着我周围的类似问题,我确信自己必须自己编译libcurl。
实际上,解决方案是使用:
char *response = (char *)malloc( sizeof(*response) * 100 );
而不是:
char *response;