我正在使用 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 的参数是一个字符串。
最佳答案
试试下面的代码
public func testApi(){
//replace "application/x-www-form-urlencoded" with "application/json"
//let headers = ["token":self.APIkey, "Content-Type": "application/x-www-form-urlencoded"]
let headers = ["token":self.APIkey, "Content-Type": "application/json"]
let url = "https://sandbox.rapidid.com.au/dvs/driverLicence"
let bodyString: [String: Any] = [
"BirthDate": "1985-02-08",
"GivenName": "mary",
"FamilyName": "lee",
"LicenceNumber": "94977000",
"StateOfIssue": "ACT"
]
//I think you don't want "Body" in request
//let params : [String: Any] = ["Body": bodyString]
//replace params with bodyString
Alamofire.request(url, method: .post, parameters: bodyString, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
if let apiResponse = response.result.value as? [String : AnyObject] {
print("params is \(bodyString)")
if apiResponse["exceptionId"] as? String == nil {
print(apiResponse)
return
}
}
}
}
关于json - Swift 和 Alamofire API 调用 : trouble reading parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47972728/