使用 SwiftyJSON 对 Alamofire GET 参数进行 URL 编码
Posted
技术标签:
【中文标题】使用 SwiftyJSON 对 Alamofire GET 参数进行 URL 编码【英文标题】:URL Encode Alamofire GET params with SwiftyJSON 【发布时间】:2015-09-15 20:59:17 【问题描述】:我试图让 Alamofire 在 GET 请求中发送以下参数,但它发送的是乱码:
filters="$and":["name":"$bw":"duke","country":"gb"]
//www.example.com/example?filters="$and":["name":"$bw":"duke","country":"gb"]
//Obviously URL encoded
这是我的代码:
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
print(json)
输出
“$和”:[ “姓名” : “$bw”:“公爵” , “国家”:“国标” ]
这是我的参数请求:
let params = ["filters" : json.rawValue, "limit":"1", "KEY":"my_key"]
这是 AlamoFire 发送的内容:
KEY=my_key&
filters[$and][][country]=gb&
filters[$and][][name][$bw]=duke&
limit=1
如您所见,过滤器参数完全是一团糟。我做错了什么?
【问题讨论】:
您能在这里复制一下您是如何使用 Alamofire 发送此请求的吗?这个请求不是使用 GET 发送的吗?也许您可以尝试使用 POST 方法? 必须得到。我用.request(.GET, url, params)
【参考方案1】:
默认情况下,Alamofire 使用 POST 正文中的参数列表对参数进行编码。尝试将编码更改为JSON
。这样,Alamofire 将按照您的预期将字典序列化为 JSON 字符串:
let parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)
// HTTP body: "foo": [1, 2, 3], "bar": "baz": "qux"
或使用您的代码:
let string = "duke"
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
let params = ["filters" : json.rawValue, "limit":"1", "KEY":"my_key"]
Alamofire.request(.POST, "http://httpbin.org/post", parameters: params, encoding: .JSON)
.responseString(encoding: NSUTF8StringEncoding) request, response, content, error in
NSLog("Request: %@ - %@\n%@", request.HTTPMethod!, request.URL!, request.HTTPBody.map body in NSString(data: body, encoding: NSUTF8StringEncoding) ?? "" ?? "")
if let response = response
NSLog("Response: %@\n%@", response, content ?? "")
获取输出:
Request: POST - http://httpbin.org/post
"filters":"$and":["name":"$bw":"duke","country":"gb"],"limit":"1","KEY":"my_key"
编辑:GET 参数中的 URL 编码 JSON
如果您想在 GET 参数中发送一个 URL 编码的 JSON,您必须首先生成 JSON 字符串,然后将其作为字符串传递到您的参数字典中:
SWIFT 1
let string = "duke"
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
// Generate the string representation of the JSON value
let jsonString = json.rawString(encoding: NSUTF8StringEncoding, options: nil)!
let params = ["filters" : jsonString, "limit": "1", "KEY": "my_key"]
Alamofire.request(.GET, "http://httpbin.org/post", parameters: params)
.responseString(encoding: NSUTF8StringEncoding) request, response, content, error in
NSLog("Request: %@ - %@\n%@", request.HTTPMethod!, request.URL!, request.HTTPBody.map body in NSString(data: body, encoding: NSUTF8StringEncoding) ?? "" ?? "")
if let response = response
NSLog("Response: %@\n%@", response, content ?? "")
SWIFT 2
let string = "duke"
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
// Generate the string representation of the JSON value
let jsonString = json.rawString(NSUTF8StringEncoding)!
let params = ["filters" : jsonString, "limit": "1", "KEY": "my_key"]
Alamofire.request(.GET, "http://httpbin.org/post", parameters: params)
.responseString(encoding: NSUTF8StringEncoding) request, response, result in
NSLog("Request: %@ - %@\n%@", request!.HTTPMethod!, request!.URL!, request!.HTTPBody.map body in NSString(data: body, encoding: NSUTF8StringEncoding) ?? "" ?? "")
switch result
case .Success(let value):
NSLog("Response with content: %@", value)
case .Failure(let data, _):
NSLog("Response with error: %@", data ?? NSData())
SWIFT 3 和 Alamofire 4.0
let string = "duke"
let jsonObject = ["$and":[["name":["$bw":string], "country":"gb"]]]
let json = JSON(jsonObject)
// Generate the string representation of the JSON value
let jsonString = json.rawString(.utf8)!
let params = ["filters" : jsonString, "limit": "1", "KEY": "my_key"]
Alamofire.request("http://httpbin.org/post", method: .get, parameters: params)
.responseString response in
#if DEBUG
let request = response.request
NSLog("Request: \(request!.httpMethod!) - \(request!.url!.absoluteString)\n\(request!.httpBody.map body in String(data: body, encoding: .utf8) ?? "" ?? "")")
switch response.result
case .success(let value):
print("Response with content \(value)")
case .failure(let error):
print("Response with error: \(error as NSError): \(response.data ?? Data())")
#endif
这会生成一个带有以下 URL 的 GET 请求:
http://httpbin.org/post?KEY=my_key&filters=%7B%22%24and%22%3A%5B%7B%22name%22%3A%7B%22%24bw%22%3A%22duke%22%7D%2C%22country%22%3A%22gb%22%7D%5D%7D&limit=1
那个 URL-Decoded 是:
http://httpbin.org/post?KEY=my_key&filters="$and":["name":"$bw":"duke","country":"gb"]&limit=1
【讨论】:
谢谢(我应该在问题中指定抱歉)但我需要做一个获取请求。它还需要看起来像这样: "filters":""$and":["name":"$bw":"duke","country":"gb"]","limit ":"1","KEY":"my_key".... 不知道是谁写的 API... 我会在问题中说得更清楚。 因此您需要一个 JSON 字符串作为 GET URL 中的 URL 编码参数。这完全改变了这个问题。查看我的编辑,看看是否符合您的需求。 谢谢,太好了!我必须编辑的一件事是let jsonString = json.rawString(NSUTF8StringEncoding, options: .PrettyPrinted)!
,因为你不能提供nil
,而且第一个标签是无关的。我将对其进行编辑并编辑问题以使其他人更清楚。
@MobileBloke 添加了 Swift 3 版本
我在 swift 上看到的更好的帖子之一,感谢发帖。以上是关于使用 SwiftyJSON 对 Alamofire GET 参数进行 URL 编码的主要内容,如果未能解决你的问题,请参考以下文章
在 Swift 中将 Alamofire 结果解析为对象(使用:Alamofire、SwiftyJSON 和 ObjectMapper)
swift、Alamofire、SwiftyJSON:如何解析 arrayObject