gpt4 book ai didi

swift - URLComponents queryItems 在突变时丢失百分比编码

转载 作者:搜寻专家 更新时间:2023-11-01 07:06:06 29 4
gpt4 key购买 nike

当使用 URLComponentsqueryItems 时,我发现如果您有一个查询项,其值包含一些百分比编码字符,在我的例子中是 / 被编码为 %2F,那么如果您从包含此类查询项的 String URL 构造一个 URLComponents 对象,则改变 URLComponents 对象的查询项列表,然后如果您尝试通过调用 URLComponents 上的 .url 来获取 URL 对象,则查询项将丢失其百分比编码。

这是我在 Playground 上测试过的代码:

import UIKit

// --- Part 1 ---
print("--- Part 1 ---\n")

let startURL = "https://test.com/test.jpg?X-Test-Token=FQdzEPH%2F%2F%2F"
var components = URLComponents(string: startURL)!

if let compURL = components.url {
print(URL(string: startURL)! == compURL) // True
print(startURL)
print(compURL)
}

// --- Part 2 ---
print("\n--- Part 2 ---\n")

let startURLTwo = "https://test.com/test.jpg?X-Test-Token=FQdzEPH%2F%2F%2F"
let finalURL = "https://test.com/test.jpg?X-Test-Token=FQdzEPH%2F%2F%2F&foo=bar"
var componentsTwo = URLComponents(string: startURLTwo)!

let extraQueryItem = URLQueryItem(name: "foo", value: "bar")
componentsTwo.queryItems!.append(extraQueryItem)

if let compURLTwo = componentsTwo.url {
print(URL(string: finalURL)! == compURLTwo) // False
print(finalURL)
print(compURLTwo)
}

如果可以更容易地理解正在发生的事情,这里有一张图片:

enter image description here

最佳答案

如果你有一个已经被百分比编码的查询,你应该使用 percentEncodedQuery:

let startURL = "https://test.com/test.jpg"
var components = URLComponents(string: startURL)!
components.percentEncodedQuery = "X-Test-Token=FQdzEPH%2F%2F%2F"

if let compURL = components.url {
print(compURL)
}

或者您可以将其指定为未转义(并且它保持未转义,因为不必在查询中转义 / 字符):

let startURL = "https://test.com/test.jpg"
var components = URLComponents(string: startURL)!
components.queryItems = [URLQueryItem(name: "X-Test-Token", value: "FQdzEPH///")]

if let compURL = components.url {
print(compURL)
}

如果您必须更新 queryItems,只需确保在最后设置 percentEncodedQuery:

let startURL = "https://test.com/test.jpg"
let encodedQuery = "X-Test-Token=FQdzEPH%2F%2F%2F"
var components = URLComponents(string: startURL)!
components.queryItems = [URLQueryItem(name: "foo", value: "bar, baz, & qux")]
if let query = components.percentEncodedQuery {
components.percentEncodedQuery = query + "&" + encodedQuery
} else {
components.percentEncodedQuery = encodedQuery
}

if let compURL = components.url {
print(compURL)
}

关于swift - URLComponents queryItems 在突变时丢失百分比编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47932235/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com