我需要这样的 URL 才能工作:
我用来生成 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)
打印:
服务器主机出错,因为 POINT(-104.23828125%252039.90973623454)
有 %25
而不是只有 %
。
如何生成只有 %
的项目 POINT(-104.23828125%2039.90973623454)
?
最佳答案
看起来您正在尝试使用 Wind Toolkit Data API . (截至 2023 年 1 月的更新:这是撰写此问题时原始链接的样子:Wind Toolkit Data API)
在您写这个问题时,在他们的一个示例请求中,该页面有一个如下所示的查询参数:
wkt=POINT(-104.23828125%2039.90973623453719)
%20
实际上只是一个 URL-encoded空格字符。
(是他们如何为 wkt
参数显示 URL 编码值,但对于值包含空格的其他参数,如 full_name =Sample User
或 affiliation=Test Organization
,所以混淆的来源是可以理解的。)
无论如何,要解决此问题,只需将 wktStr
中的 %
字符替换为空格即可:
let wktStr: String = "POINT("+formattedX+" "+formattedY+")"
关于swift - 如何对 URL 进行编码以在 Swift 中传递百分比 (%) 符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61666596/