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 }

 

posted on 2015-12-15 14:58  阳台  阅读(1277)  评论(0编辑  收藏  举报

导航