curl.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include "curl.h"
  2. // Borrowed from https://curl.haxx.se/libcurl/c/getinmemory.html
  3. struct MemoryStruct {
  4. char *memory;
  5. size_t size;
  6. };
  7. static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
  8. size_t realsize = size * nmemb;
  9. struct MemoryStruct *mem = (struct MemoryStruct *)userp;
  10. mem->memory = realloc(mem->memory, mem->size + realsize + 1);
  11. if(mem->memory == NULL)
  12. return 0;
  13. memcpy(&(mem->memory[mem->size]), contents, realsize);
  14. mem->size += realsize;
  15. mem->memory[mem->size] = 0;
  16. return realsize;
  17. }
  18. char *getData(char *url) {
  19. CURL *curl_handle;
  20. CURLcode res;
  21. struct MemoryStruct chunk;
  22. chunk.memory = malloc(1); /* will be grown as needed by the realloc above */
  23. chunk.size = 0; /* no data at this point */
  24. curl_global_init(CURL_GLOBAL_ALL);
  25. /* init the curl session */
  26. curl_handle = curl_easy_init();
  27. /* specify URL to get */
  28. curl_easy_setopt(curl_handle, CURLOPT_URL, url);
  29. curl_easy_setopt(curl_handle, CURLOPT_NOPROXY, "*");
  30. /* send all data to this function */
  31. curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
  32. /* we pass our 'chunk' struct to the callback function */
  33. curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
  34. /* some servers don't like requests that are made without a user-agent
  35. field, so we provide one */
  36. curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
  37. #ifdef WIN32
  38. curl_easy_setopt(curl_handle, CURLOPT_CAINFO, "cacert.pem");
  39. #endif
  40. /* get it! */
  41. res = curl_easy_perform(curl_handle);
  42. /* check for errors */
  43. if(res != CURLE_OK) {
  44. fprintf(stderr, "curl_easy_perform() failed: %s\n",
  45. curl_easy_strerror(res));
  46. }
  47. /* cleanup curl stuff */
  48. curl_easy_cleanup(curl_handle);
  49. /* we're done with libcurl, so clean it up */
  50. curl_global_cleanup();
  51. return chunk.memory;
  52. }