gpt4 book ai didi

curl - 使用cURL崩溃

转载 作者:行者123 更新时间:2023-12-03 17:26:53 25 4
gpt4 key购买 nike

我正在使用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:

Source: {"current_bac":0,"time_until_sober":0}

0

Response: {"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}



我究竟做错了什么?

最佳答案

老兄,看着周围的类似问题,我确定自己必须自己编译libcurl。

实际上,解决方案是使用:

char *response = (char *)malloc( sizeof(*response) * 100 );

代替:
char *response;

关于curl - 使用cURL崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26074583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com