parseurl.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2020, 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. * Basic URL API use.
  24. * </DESC>
  25. */
  26. #include <stdio.h>
  27. #include <curl/curl.h>
  28. #if !CURL_AT_LEAST_VERSION(7, 62, 0)
  29. #error "this example requires curl 7.62.0 or later"
  30. #endif
  31. int main(void)
  32. {
  33. CURLU *h;
  34. CURLUcode uc;
  35. char *host;
  36. char *path;
  37. h = curl_url(); /* get a handle to work with */
  38. if(!h)
  39. return 1;
  40. /* parse a full URL */
  41. uc = curl_url_set(h, CURLUPART_URL, "http://example.com/path/index.html", 0);
  42. if(uc)
  43. goto fail;
  44. /* extract host name from the parsed URL */
  45. uc = curl_url_get(h, CURLUPART_HOST, &host, 0);
  46. if(!uc) {
  47. printf("Host name: %s\n", host);
  48. curl_free(host);
  49. }
  50. /* extract the path from the parsed URL */
  51. uc = curl_url_get(h, CURLUPART_PATH, &path, 0);
  52. if(!uc) {
  53. printf("Path: %s\n", path);
  54. curl_free(path);
  55. }
  56. /* redirect with a relative URL */
  57. uc = curl_url_set(h, CURLUPART_URL, "../another/second.html", 0);
  58. if(uc)
  59. goto fail;
  60. /* extract the new, updated path */
  61. uc = curl_url_get(h, CURLUPART_PATH, &path, 0);
  62. if(!uc) {
  63. printf("Path: %s\n", path);
  64. curl_free(path);
  65. }
  66. fail:
  67. curl_url_cleanup(h); /* free url handle */
  68. return 0;
  69. }