headerapi.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. /* <DESC>
  23. * Extract headers post transfer with the header API
  24. * </DESC>
  25. */
  26. #include <stdio.h>
  27. #include <curl/curl.h>
  28. static size_t write_cb(char *data, size_t n, size_t l, void *userp)
  29. {
  30. /* take care of the data here, ignored in this example */
  31. (void)data;
  32. (void)userp;
  33. return n*l;
  34. }
  35. int main(void)
  36. {
  37. CURL *curl;
  38. curl = curl_easy_init();
  39. if(curl) {
  40. CURLcode res;
  41. struct curl_header *header;
  42. curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
  43. /* example.com is redirected, so we tell libcurl to follow redirection */
  44. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  45. /* this example just ignores the content */
  46. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
  47. /* Perform the request, res will get the return code */
  48. res = curl_easy_perform(curl);
  49. /* Check for errors */
  50. if(res != CURLE_OK)
  51. fprintf(stderr, "curl_easy_perform() failed: %s\n",
  52. curl_easy_strerror(res));
  53. if(CURLHE_OK == curl_easy_header(curl, "Content-Type", 0, CURLH_HEADER,
  54. -1, &header))
  55. printf("Got content-type: %s\n", header->value);
  56. printf("All server headers:\n");
  57. {
  58. struct curl_header *h;
  59. struct curl_header *prev = NULL;
  60. do {
  61. h = curl_easy_nextheader(curl, CURLH_HEADER, -1, prev);
  62. if(h)
  63. printf(" %s: %s (%u)\n", h->name, h->value, (int)h->amount);
  64. prev = h;
  65. } while(h);
  66. }
  67. /* always cleanup */
  68. curl_easy_cleanup(curl);
  69. }
  70. return 0;
  71. }