如何在Swift中创建URL时保留方括号?

huangapple go评论95阅读模式
英文:

How to preserve square brackets while creating an URL in Swift?

问题

如何创建URL对象,但保留方括号而不将其转换为%5B和%5D。 谢谢!

英文:

I have let urlString = "https://example.com/[path]/file.txt".
How to create URL object, but preserve square brackets and not converting it to %5B and %5D.
Thank you!

答案1

得分: 1

TL;DR: 根据设计,您不能这样做。这不是有效的URL,因此无法用 URL 表达。

Long version:

URI(包括URL)的路径部分由RFC 3986 Section 3.3定义。每个段(在 / 之间)中允许的字符称为 pchar,定义如下:

pchar       = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims  = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

[] 不在此列表中,因此不能出现在路径中。您必须进行百分比编码。

您可以创建包括这些字符的字符串,但它不能是URL。

英文:

TL;DR: You can't, by design. That isn't a valid URL, so it can't be expressed with URL.

Long version:

The path component of a URI (including URLs) is defined by RFC 3986 Section 3.3. The allowed characters in each segment (between /) are called pchar, defined as follows:

pchar       = unreserved / pct-encoded / sub-delims / ":" / "@"
unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"
pct-encoded = "%" HEXDIG HEXDIG
sub-delims  = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="

[ and ] are not on that list, and so cannot be in the path. You must percent-encode them.

You are free to create a String that includes those characters, but it cannot be an URL.

huangapple
  • 本文由 发表于 2023年2月23日 22:59:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定