首页 > 解决方案 > 如何对 URL 进行编码以在 Swift 中传递百分比 (%) 符号?

问题描述

我需要这样的 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=sample@email.com&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: "sample@email.com"),
    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=sample@email.com&affiliation=TestOrganization&reason=Dev

服务器主机给出错误,因为POINT(-104.23828125%252039.90973623454)has%25而不是 just %

如何生成POINT(-104.23828125%2039.90973623454)只有 的项目%

标签: swifturl

解决方案


看起来您正在尝试使用Wind Toolkit Data API

在他们的一个示例请求中,他们有一个查询参数,显示如下:

wkt=POINT(-104.23828125%2039.90973623453719)

%20实际上只是一个URL 编码的空格字符。

(它们如何显示参数的 URL 编码值有点令人困惑wkt但对于其值包含空格之类的其他参数则不是这样full_name=Sample Useror affiliation=Test Organization,因此混淆的来源是可以理解的。)

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

let wktStr: String = "POINT("+formattedX+" "+formattedY+")"

推荐阅读