0
我在嘗試與libcurl發送GET請求到服務器並保存響應。當我不使用CURLOPT_WRITEFUNCTION和CURLOPT_WRITEFDATA時,它正常工作,響應轉到標準流,程序在按下按鈕後關閉。Appcrash與捲曲
當我添加自己的函數和一個變量來保存響應,但是,響應結束時會出現額外的垃圾字符,並且程序在按下按鈕後崩潰。
#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}
響應:{ 「current_bac」:0 「time_until_sober」:0} p
如果IC omment出以下行(和一個printf):
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWrite);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, response);
我得到這個:
{ 「current_bac」:0, 「time_until_sober」:0}
我是什麼做錯了?