ios - swift PUT API 调用缺少参数

标签 ios json swift api

我不断收到错误代码 400:缺少参数 我相信问题在于我发送数据的格式

API 文档:http://middleware.idxbroker.com/docs/api/methods/index.html#api-Leads-putLead

我认为通话所需的必填数据是名字、姓氏和电子邮件,我是否需要将其他字段发送为零,或者可以将它们留空吗?

API调用

/// Send Lead to IDX Broker
///
/// - Parameter lead: new Lead data fields
/// - Returns: configs for URL Session
class func putLead(lead: String) -> URLRequest {

    let urlString = "https://api.idxbroker.com/leads/lead"
    let url = NSURL(string: urlString)

    var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
    /******************** Add Headers required for API CALL *************************************/
    downloadTask.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    downloadTask.setValue(APICalls.getAccessKey(), forHTTPHeaderField: "accesskey")
    downloadTask.setValue("json", forHTTPHeaderField: "outputtype")
    downloadTask.httpMethod = "PUT"
    downloadTask.httpBody = lead.data(using: .utf8)
    /******************** End Headers required for API CALL *************************************/

    return downloadTask
}

数据发送到函数

 /// Create lead from text fields
    let postString = "lead(firstName=\(String(describing: firstName.text!))&lastName=\(String(describing: lastName.text!))&=email=\(String(describing: Email.text!)))"

    /// URL Encoding for put API
    let escapedString = postString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
    print(escapedString!)
    print(escapedString?.data(using: .utf8) ?? "Error")

    /// API Call with passing json String
    let downloadTask = APICalls.putLead(lead: escapedString!)


    URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in

        /// Status Returned from API CALL
        if let httpResponse = response as? HTTPURLResponse {
            print("statusCode: \(httpResponse.statusCode)")
        }


    }).resume()
    /******** End URL Session **********/

最佳答案

400 表示 API 未获取或未获取您传递的更多参数。如果 API 收到了firstName,那么它将返回一个错误,指出未收到lastName。如果通过了第一个和最后一个,那么它将回复未收到电子邮件。

测试您的代码,当我没有在 postString 中使用 Lead() 时,我能够获得预期的字符串。

关于ios - swift PUT API 调用缺少参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43667923/

相关文章:

iOS swift : Getting repeated value while updating 2D Array in custom UITableView cell

ios - ios 7 中的 uitableview 在状态栏上方滚动

ios - 无法使用 Swift 连接 RabbitMQ

ios - iPhone永久数据存储

c# - 如何使用 .NET 解析此第 3 方 JSON 服务?

json - ExtJS:JsonStore 根本没有加载

swift - 无法在圆圈中创建 108 个点

ios - View Controller 中的依赖注入(inject)

java - 使用 volley 库获取具有整数的 json

ios - 从 Objective-C 迁移到 Swift : AFNetworking > Alamofire