我如何在Swift中对URL进行编码以传递百分比(%)符号?

问题描述 投票:0回答:1

我需要一个这样的URL来工作。

https:/somehost.govapiwtk_download.csv?api_key=DEMO_KEY&wkt=POINT(-104.23828125%252039.90973623454)&属性=power&names=2009&interval=60&full_name=SampleUser&[email protected]&affiliation=TestOrganization&reason=Dev。

我用来生成URL的代码。

let wktStr: String = "POINT("+formattedX+"%"+formattedY+")"
var components = URLComponents()
components.scheme = "https"
components.host = "somehost.gov"
components.path = "/api/wtk_download.csv"
components.queryItems = [
    URLQueryItem(name: "api_key", value: "DEMO_KEY"),
    URLQueryItem(name: "wkt", value: wktStr),
    URLQueryItem(name: "attributes", value: "power"),
    URLQueryItem(name: "names", value: yearString),
    URLQueryItem(name: "interval", value: "60"),
    URLQueryItem(name: "full_name", value: "SampleUser"),
    URLQueryItem(name: "email", value: "[email protected]"),
    URLQueryItem(name: "affiliation", value: "TestOrganization"),
    URLQueryItem(name: "reason", value: "Dev")

]

let url = components.url
print(url!)
print(url!.absoluteURL)

打印。

https:/somehost.govapiwtk_download.csv?api_key=DEMO_KEY&wkt=POINT(-104.23828125%252039.90973623454)&属性=power&names=2009&interval=60&full_name=SampleUser&[email protected]&affiliation=TestOrganization&reason=Dev。

服务器主机给出了一个错误,因为 POINT(-104.23828125%252039.90973623454)%25 而不是仅仅 %.

如何生成项目 POINT(-104.23828125%2039.90973623454) 其中正好有 %?

swift url
1个回答
1
投票

看来你是想用 Wind工具箱数据API.

在他们的一个示例请求中,他们有一个查询参数,他们显示的是这样的。

wkt=POINT(-104.23828125%2039.90973623453719)

这个 %20 其实只是 URL编码 空间字符。

(它 有点困惑,他们如何显示一个URL编码的值为 wkt 参数,但对于其他值包含空格的参数,如 full_name=Sample Useraffiliation=Test Organization所以可以理解困惑的来源)。)

总之,要解决这个问题,只需将下面的 % 字样 wktStr 与空间。

let wktStr: String = "POINT("+formattedX+" "+formattedY+")"
© www.soinside.com 2019 - 2024. All rights reserved.