【发布时间】:2019-03-12 06:09:51
【问题描述】:
我正在尝试发送一个需要如下所示的 api 请求:
https://api.gibbly.com/1/device?format=json&body={"selection"={"selectionType":"registered","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 尝试了请求,它工作正常,所以我认为问题是由代码引起的。
根据代码中的第一个“打印”语句,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)
}
【问题讨论】:
-
你确定那是 API 格式吗?看起来您正在发送作为查询字符串一部分的 HTTP 正文中的数据
-
如果您在 GET 请求中发送参数,请尝试使用 content-type
application/json,如果不使用URLEncoding.default作为编码。
标签: swift httprequest alamofire