Swift和Alamofire API调用:读取参数时遇到麻烦

问题描述 投票:0回答:2

我正在使用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的参数,这是一个字符串。

json swift api alamofire
2个回答
1
投票

尝试以下代码

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
                }
            }
    }
}

0
投票

通常,当通过传递JSON数据发出POST请求时,数据将在正文中传递。

... API文档说应该传递一个名为Body的参数,它是一个字符串

如果我理解正确,那么API期望在post请求的主体中使用JSON数据。

看起来你没有正确编码JSON。这是如何解决它...

public func testApi() {

    let headers = ["token":self.APIkey, "Content-Type": "application/x-www-form-urlencoded"]
    let url = self.testApiUrl

    let bodyString: [String: Any] = [
        "BirthDate": "1985-02-08",
        "GivenName": "mary",
        "FamilyName": "lee",
        "LicenceNumber": "94977000",
        "StateOfIssue": "ACT"
    ]
    let params : [String: Any] = ["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
                }
            }
    }
}

希望这可以解决它。但是,如果您需要将JSON作为参数传递,则需要将其编码到URL中。看看这个answer

© www.soinside.com 2019 - 2024. All rights reserved.