我正在尝试发送一个如下所示的api请求:
https://api.gibbly.com/1/device?format=json&body= {“ selection” = {“ selectionType”:“已注册”,“ selectionMatch”:“”,“ includeRuntime”:true}}
但是,当我使用下面的代码时,出现错误。在响应的[RESULT]部分中,我得到以下信息:
[RESULT] FAILURE: responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
我尝试使用Postman进行请求,并且效果很好,所以我认为问题是由代码引起的。
基于代码中的第一个“ print”语句,HTTP正文似乎是正确的:
Optional({"selection":{"selectionType":"registered","selectionMatch":"","includeSettings":true}})
我唯一能想到的是Alamofire并未在请求中添加“ format = json&body =“,但我不知道该如何看待。任何帮助将不胜感激。
let headers: HTTPHeaders = [
"Authorization": "Bearer adsf023494axadf32342",
"Content-Type": "text/json"
]
let parameters: [String: Any] = [
"selection":[
"selectionType":"registered",
"selectionMatch":"",
"includeSettings":true
]
]
Alamofire.request(url!, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON {
response in
print(NSString(data: (response.request?.httpBody)!, encoding: String.Encoding.utf8.rawValue))
print(response)
}
答案 0 :(得分:0)
对于GET方法,在Alamofire请求中使用URLEncoding.default而不是JSONEncoding.default
答案 1 :(得分:0)
好了。我做了以下工作:(1)将参数创建为字符串,(2)对它们进行百分比编码,以便所有字符都可以用作url,(3)将编码后的参数添加到基本url,以及(4)使用新网址,其中包含基本网址,然后将编码后的参数作为我请求的网址。
let url = "https://api.gibbly.com/1/device?format=json&body="
let urlParams = "{\"selection\":{\"selectionType\":\"registered\",\"selectionMatch\":\"\",\"includeSettings\":true}}"
let urlEncoded = url + urlParams.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let headerList : HTTPHeaders = [
"Authorization" : "Bearer " + (KeychainWrapper.standard.string(forKey: "accessToken"))!,
"Content-Type" : "text/json"
]
Alamofire.request(urlEncoded, method: .get, headers: headerList).responseJSON{
response in
print(response)
}