swift - 如何对 URL 进行编码以在 Swift 中传递百分比 (%) 符号?
问题描述
我需要这样的 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)
has%25
而不是 just %
。
如何生成POINT(-104.23828125%2039.90973623454)
只有 的项目%
?
解决方案
看起来您正在尝试使用Wind Toolkit Data API。
在他们的一个示例请求中,他们有一个查询参数,显示如下:
wkt=POINT(-104.23828125%2039.90973623453719)
这%20
实际上只是一个URL 编码的空格字符。
(它们如何显示参数的 URL 编码值有点令人困惑,wkt
但对于其值包含空格之类的其他参数则不是这样full_name=Sample User
or affiliation=Test Organization
,因此混淆的来源是可以理解的。)
无论如何,要解决此问题,只需将%
您的字符替换wktStr
为空格:
let wktStr: String = "POINT("+formattedX+" "+formattedY+")"
推荐阅读
- javascript - 有没有办法 console.log 一个 html 对象的内容?
- reactjs - API调用一旦执行就返回promise对象?
- mysql - 如何将我的路由参数与@mysql/x devAPI 连接起来?
- c# - 如何按照 Fluent Builder 模式使用回调将值添加到上下文
- mysql - SQL 选择多于 1 个联结的地方
- java - 如何解决连接有空值?
- ios - 我们是否需要通过应用内购买来接受付款?
- laravel - Laravel 删除方法在 yajra 数据表上给出“方法不允许”错误
- wordpress - 仅向 WordPress 多站点管理员授予编辑者角色
- c - C Ctrl+D 重定向做 smtg else