我正在尝试使用绑定到它的json对象执行GET请求,这是我如何生成JSON对象
let jsonObject: [String: AnyObject] = [
"ean_code": [
"type": "match",
"value": "16743799"
]
]
然后我执行了请求
像这样 Alamofire.request(.GET,Constant.WebClient.WS_URL + "/product?filters="+String(jsonObject),parameters:parameters)
但是这给了我一个错误,即错误地将URL绑定到无效字符
所以我编码了这个
的网址let request = String(jsonObject).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPasswordAllowedCharacterSet())!
这将对URL进行编码,但我会再次给出以下错误
请求失败并显示错误:错误Domain = NSCocoaErrorDomain Code = 3840“字符0周围的值无效。” UserInfo = {NSDebugDescription =字符0周围的值无效。}
所以我的问题是如何将json对象绑定到GET URL?
答案 0 :(得分:1)
做这样的事情
let parameters: [String: AnyObject] = [
"filters": "merchantName",
"ean_code": [
"type": "match",
"value": "16743799"
]
]
do {
let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: .PrettyPrinted)
let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
let urlEncodedJson = jsonString!.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let urlString = "http://www.filter.com/¶ms=\(urlEncodedJson!)"
let url = NSURL(string: urlString)
// Trigger alaomofire request with url
}
catch let JSONError as NSError {
print("\(JSONError)")
}
答案 1 :(得分:0)
尝试:
func encode(json: [String: AnyObject]) -> NSMutableURLRequest {
let request: NSMutableURLRequest = ...
if let URLComponents = NSURLComponents(URL: request.URL!, resolvingAgainstBaseURL: false) {
let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(json)
URLComponents.percentEncodedQuery = percentEncodedQuery
request.URL = URLComponents.URL
return request
}
func query(parameters: [String: AnyObject]?) -> String {
guard let parameters = parameters else {
return ""
}
var components: [(String, String)] = []
for key in parameters.keys.sort(<) {
let value = parameters[key]!
components += queryComponents(key, value)
}
return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.append((key, "\(value)"))
}
return components
}
将其用作:
Alamofire.request(encode(json))
这只是代码snipets,所以你必须把它放在适当的位置:)
答案 2 :(得分:0)
您似乎尝试以两种方式添加查询参数:
当您正在执行GET
请求时,您的参数应该都是URL编码,因为GET请求不应该有正文。为什么不将filters
查询添加到参数中?
let parameters: [String: AnyObject] = [
"ean_code": [
"type": "match",
"value": "16743799"
]
]
Alamofire.request(.GET, Constant.WebClient.WS_URL + "/product", parameters: parameters)