【问题标题】:Swift and Alamofire API calls: trouble reading parametersSwift 和 Alamofire API 调用:读取参数时遇到问题
【发布时间】: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 在下面查看我的答案

标签: json swift api alamofire


【解决方案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
                }
            }
    }
}

【讨论】:

    【解决方案2】:

    通常当通过传递 JSON 数据进行 POST 请求时,数据在正文中传递。

    ...API 文档说应该传递 1 个称为 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

    【讨论】:

    • 非常感谢您的回复。这返回了相同的错误响应。我将尝试查看您建议的 URL 编码
    • 实际上并不是所有的参数都是字符串。有些期望值,请确保您不会不小心将所有内容都设为字符串。
    • 这意味着它们都需要是一个字符串并且它们都需要一个值。嗯。
    猜你喜欢
    • 2018-07-31
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    相关资源
    最近更新 更多