使用 uri 將 URI 編碼為字串
任務
網頁程式設計 / URL 和 URI 處理 / 將 URI 編碼為字串
使用的 Opam 套件
- uri 使用版本測試:4.2.0 — 使用的函式庫:uri
程式碼
為了編碼 URI,我們使用 Uri.make
函式,其參數皆為可選(除了最後的 ()
)。
let uri =
Uri.make
~scheme:"https"
~userinfo:"login:password"
~host:"ocaml.org"
~port:8080
~path:"/search"
~query:["param1",["a";"b"];"param2",["déjà "]]
~fragment:"anchor"
()
let () =
assert (Uri.to_string uri
= "https://login:password@ocaml.org:8080/search?param1=a,b¶m2=d%C3%A9j%C3%A0%20#anchor")
另一種方法是從已知的 URI 開始,並更改其某些元件。
以下函式可用:with_scheme
、with_userinfo
、with_password
、with_port
、with_path
、with_query
和 with_fragment
。
除了 with_path
和 with_query
之外,所有函式都接受一個 option
類型的參數,以便從 URI 中移除該特定元件。
注意:這些函式的第一個參數是要修改的 URI,第二個參數包含相應欄位的新值。
let uri = Uri.of_string "https://ocaml.dev.org.tw/"
let uri' = uri
|> Fun.flip Uri.with_path "/search"
|> Fun.flip Uri.with_port (Some 8080)
|> Fun.flip Uri.with_userinfo (Some "user:password")
|> Fun.flip Uri.with_query ["param1", ["42"]]
我們也可以逐個或從列表新增參數
let uri'' = Uri.add_query_param uri' ("param2",["**"])
let uri''' = Uri.add_query_params uri'' ["param3",["?"];"param4",["&"]]