c - 如何将 curl 响应存储在 c 中的变量中

标签 c http curl

我正在尝试使用 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/

相关文章:

c - 使用 printf 打印数组,字符之间有空格

javascript - 类型错误 : First argument must be a string or Buffer.

http - 什么是 httpd <defunct>?

php - 为什么 cURL 总是返回一个状态码?

curl - 如何使用curl命令获取manifest v2 schema版本2

php - 如何使用 PHP 序列化数组(数组到查询字符串)

c++ - 无效、无效、C 和 C++

c - 正常运行时程序无法运行,但逐步调试结果是正确的

java - 当我尝试将整数值发送到 Java 函数时 JVM 崩溃

javascript - 是否有可能在发布之前重命名 html 文件输入的文件