我正在尝试使用 c 程序生成 curl get 请求。这里我需要将响应存储在一个变量中,我尝试使用以下代码。
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
function_pt(void *ptr, size_t size, size_t nmemb, void *stream){
char **response_ptr = (char**)stream;
*response_ptr = strndup(ptr, (size_t)(size *nmemb));
}
int main(void)
{
CURL *curl;
CURLcode res;
char *response =calloc(1,sizeof(char));
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, function_pt);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res=curl_easy_perform(curl);
curl_easy_cleanup(curl);
printf("%s\n",response);
}
return 0;
}
我从 http get 请求获取的数据是实时的,所以我需要继续 get 请求并以迭代的方式将值存储在变量中,这样我才能在程序的所有其他部分使用这些数据.但是下面的代码只工作一次然后退出。 我该怎么做?还有其他方法可以生成http get请求吗?
最佳答案
如果要strndup()
原始字符串,则不需要calloc()
指针,假设响应是字符串并不好因为那不一定是真的。
我会建议一个结构,您还可以在其中存储响应的长度,因此如果它不是文本而是例如 jpeg
文件,则不会发生任何坏事,您不应该调用 printf()
除非您从响应 header 中检查响应确实是文本,否则它将被 nul
终止 afaik。
关于c - 如何将 curl 响应存储在 c 中的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30372704/