headerapi.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 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. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. /* <DESC>
  25. * Extract headers post transfer with the header API
  26. * </DESC>
  27. */
  28. #include <stdio.h>
  29. #include <curl/curl.h>
  30. static size_t write_cb(char *data, size_t n, size_t l, void *userp)
  31. {
  32. /* take care of the data here, ignored in this example */
  33. (void)data;
  34. (void)userp;
  35. return n*l;
  36. }
  37. int main(void)
  38. {
  39. CURL *curl;
  40. curl = curl_easy_init();
  41. if(curl) {
  42. CURLcode res;
  43. struct curl_header *header;
  44. curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
  45. /* example.com is redirected, so we tell libcurl to follow redirection */
  46. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  47. /* this example just ignores the content */
  48. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
  49. /* Perform the request, res will get the return code */
  50. res = curl_easy_perform(curl);
  51. /* Check for errors */
  52. if(res != CURLE_OK)
  53. fprintf(stderr, "curl_easy_perform() failed: %s\n",
  54. curl_easy_strerror(res));
  55. if(CURLHE_OK == curl_easy_header(curl, "Content-Type", 0, CURLH_HEADER,
  56. -1, &header))
  57. printf("Got content-type: %s\n", header->value);
  58. printf("All server headers:\n");
  59. {
  60. struct curl_header *h;
  61. struct curl_header *prev = NULL;
  62. do {
  63. h = curl_easy_nextheader(curl, CURLH_HEADER, -1, prev);
  64. if(h)
  65. printf(" %s: %s (%u)\n", h->name, h->value, (int)h->amount);
  66. prev = h;
  67. } while(h);
  68. }
  69. /* always cleanup */
  70. curl_easy_cleanup(curl);
  71. }
  72. return 0;
  73. }