我不断收到错误代码 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/