【发布时间】:2018-06-06 22:48:41
【问题描述】:
我正在使用 Alamofire 4 和 Swift 4。我正在尝试发出一个 API 请求,该请求传递了一个名为 Body 的参数,它是一个 JSON 字符串。 JSON 字符串应如下所示:
{
"BirthDate": "1985-02-08",
"GivenName": "mary",
"FamilyName": "lee",
"LicenceNumber": "94977000",
"StateOfIssue": "ACT"
}
我的代码在调试控制台中返回以下结果:
{
"result" : {
"statuscode" : "400",
"error" : [
"GivenName needs to be a string",
"FamilyName needs to be a string",
"BirthDate needs to be a string",
"LicenceNumber needs to be a string",
"StateOfIssue needs to be a string",
"MiddleName needs to be a string",
"GivenName needs a value",
"FamilyName needs a value",
"BirthDate needs a value",
"LicenceNumber needs a value",
"StateOfIssue needs a value"
]
}
}
我的代码如下:
public func testApi(){
let headers = ["token":self.APIkey, "Content-Type": "application/x-www-form-urlencoded"]
let url = self.testApiUrl
let bodyString : String = "{\"BirthDate\":\"1985-02-08\",\"GivenName\":\"mary\",\"FamilyName\":\"lee\",\"LicenseNumber\":\"94977000\",\"StateOfIssue\":\"ACT\"}"
let params : [String:String] = ["Body":"\(bodyString)"]
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
if let apiResponse = response.result.value as? [String : AnyObject] {
print("params is \(params)")
if apiResponse["exceptionId"] as? String == nil {
print(apiResponse)
return
}
}
}
}
有人可以帮忙吗?我尝试将 Body 字符串分解为字典级别(例如 Body: [name:Mary ... etc]),但这也不起作用,API 文档说应该传递 1 个名为 Body 的参数,它是一个字符串。
【问题讨论】:
-
@Skype Dunworth 在下面查看我的答案