我如何编码URL以在Swift中传递百分号(%)?

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

我需要这样的URL才能工作:

https://somehost.gov/api/wtk_download.csv?api_key=DEMO_KEY&wkt=POINT(-104.23828125%252039.90973623454)&attributes=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.gov/api/wtk_download.csv?api_key=DEMO_KEY&wkt=POINT(-104.23828125%252039.90973623454)&attributes=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 Toolkit Data API

在他们的一个示例请求中,他们有一个查询参数,看起来像这样:

wkt=POINT(-104.23828125%2039.90973623453719)

%20实际上只是一个URL-encoded空格字符。

((is有点令人困惑,它们如何显示wkt参数的URL编码值,但不显示其值包含full_name=Sample Useraffiliation=Test Organization等空格的其他参数,因此可以理解混乱来自。)

无论如何,要解决此问题,只需用空格替换%中的wktStr字符:

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