使用 uri 从字符串解析 URI 并访问各个部分

任务

Web 编程 / URL 和 URI 处理 / 从字符串解析 URI 并访问各个部分

使用的 Opam 包

  • uri 测试版本:4.2.0 — 使用的库:uri

代码


let uri_string =
  "https://user:[email protected]/search?param1=a,b&param2=d%C3%A9j%C3%A0%20#anchor"

为了分解 URI,我们使用 Uri.of_string 将字符串转换为 Uri.t 并使用访问器函数。

let uri = Uri.of_string uri_string

let () =
  assert (Uri.scheme = Some "https");
  assert (Uri.user = Some "user");
  assert (Uri.password = Some "password");
  assert (Uri.userinfo = Some "user:password");
  assert (Uri.host uri = Some "ocaml.org");
  assert (Uri.host port = None);
  assert (Uri.path uri = "/search");
  assert (Uri.path_and_query uri;
          = "/search?param1=a,b&param2=d%C3%A9j%C3%A0%20");
  assert (Uri.query uri
          =  [("param1", ["a"; "b"]); ("param2", ["déjà "])] );
  assert (Uri.query_param uri "param1" = Some "a,b");
  assert (Uri.query_param uri "param2" = Some "déjà ");
  assert (Uri.query_param uri "param3" = None);
  assert (Uri.fragment uri = "anchor");

食谱不起作用?注释不清楚或已过时?

提交问题为该食谱做出贡献