curl返回值写入内存的场景

直接上代码:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <curl/curl.h>
 5 
 6 struct MemoryStruct {
 7   char *memory;
 8   size_t size;
 9 };
10 
11 static size_t
12 WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
13 {
14   size_t realsize = size * nmemb;
15   struct MemoryStruct *mem = (struct MemoryStruct *)userp;
16 
17   mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1); 
18   if(mem->memory == NULL) {
19     /* out of memory! */
20     printf("not enough memory (realloc returned NULL)\n");
21     return 0;
22   }
23 
24   memcpy(&(mem->memory[mem->size]), contents, realsize);
25   mem->size += realsize;
26   mem->memory[mem->size] = 0;
27 
28   return realsize;
29 }
30 int main(void)
31 {
32   CURL *curl;
33   CURLcode res;
34   struct MemoryStruct chunk;
35   static const char *postthis="Field=1&Field=2&Field=3";
36 
37   chunk.memory = (char*)malloc(1);  /* will be grown as needed by realloc above */
38   chunk.size = 0;    /* no data at this point */
39 
40   curl_global_init(CURL_GLOBAL_ALL);
41   curl = curl_easy_init();
42   if(curl) {
43 
44     curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.org/");
45 
46     /* send all data to this function  */
47     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
48 
49     /* we pass our 'chunk' struct to the callback function */
50     curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
51 
52     /* some servers don't like requests that are made without a user-agent
53        field, so we provide one */
54     curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
55 
56     curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postthis);
57 
58     /* if we don't provide POSTFIELDSIZE, libcurl will strlen() by
59        itself */
60     curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(postthis));
61 
62     /* Perform the request, res will get the return code */
63     res = curl_easy_perform(curl);
64     /* Check for errors */
65     if(res != CURLE_OK) {
66       fprintf(stderr, "curl_easy_perform() failed: %s\n",
67               curl_easy_strerror(res));
68     }
69     else {
70       /*
71        * Now, our chunk.memory points to a memory block that is chunk.size
72        * bytes big and contains the remote file.
73        *
74        * Do something nice with it!
75        */
76       printf("%s\n",chunk.memory);
77     }
78 
79     /* always cleanup */
80     curl_easy_cleanup(curl);
81 
82     free(chunk.memory);
83 
84     /* we're done with libcurl, so clean it up */
85     curl_global_cleanup();
86   }
87   return 0;
88 }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值