gpt4 book ai didi

swift - Alamofire 2.0 的放置请求失败

转载 作者:行者123 更新时间:2023-11-30 14:04:24 25 4
gpt4 key购买 nike

我最近升级到 Alamofire 2.0,现在我的 Put 请求失败并出现 400 错误,而之前它工作正常。我使用代码执行调用:

Alamofire.request(Router.Put(query: url, params: params, encoding: .JSON))
.validate()
.responseJSON() {
(request, response, result) in

print("request: \(request)")
print("response: \(response)")
print("result: \(result)")

switch result {
case .Success(_):
// success
case .Failure(let data, _):
// error occured
}
}

和我的自定义路由器类:

enum Router: URLRequestConvertible {

case Get(query: String, params: [String: AnyObject]?)
case Post(query: String, params: [String: AnyObject]?)
case Put(query: String, params: [String: AnyObject]?, encoding: ParameterEncoding)
case Delete(query: String, params: [String: AnyObject]?)

var URLRequest: NSMutableURLRequest {
var encodeMethod: Alamofire.ParameterEncoding = Alamofire.ParameterEncoding.URL

// Default to GET
var httpMethod: String = Alamofire.Method.GET.rawValue

let (path, parameters): (String, [String: AnyObject]?) = {
switch self {
case .Get(let query, let params):
// Set the request call
httpMethod = Alamofire.Method.GET.rawValue
// Return the query
return (query, params)
case .Post(let query, let params):
// Set the request call
httpMethod = Alamofire.Method.POST.rawValue
// Return the query
return (query, params)
case .Put(let query, let params, let encoding):
// Set the request call
httpMethod = Alamofire.Method.PUT.rawValue
// Set the encoding
encodeMethod = encoding
// Return the query
return (query, params)
case .Delete(let query, let params):
// Set the request call
httpMethod = Alamofire.Method.DELETE.rawValue
// Return the query
return (query, params)
}
}()

// Create the URL Request
let URLRequest = NSMutableURLRequest(URL: NSURL(string: Globals.BASE_URL + path)!)
// set header fields
if let key = NSUserDefaults.standardUserDefaults().stringForKey(Globals.NS_KEY_SESSION) {
URLRequest.setValue(key, forHTTPHeaderField: "X-XX-API")
}
// Add user agent
if let userAgent = NSUserDefaults.standardUserDefaults().stringForKey(Globals.NS_KEY_USER_AGENT) {
URLRequest.setValue(userAgent, forHTTPHeaderField: "User-Agent")
}

// Set the HTTP method
URLRequest.HTTPMethod = httpMethod

URLRequest.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData

return encodeMethod.encode(URLRequest, parameters: parameters).0
}
}

响应不是调用成功,而是:

response: Optional(<NSHTTPURLResponse: 0x7fcee15b34d0> { URL: https://apiurl } { status code: 400, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 26;
"Content-Type" = "application/json; charset=utf-8";
Date = "Tue, 15 Sep 2015 15:33:50 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/8.5";
} })

我调查了这个问题,在服务器端,Content-Type 对于请求来说是空白的,而它应该以 application/json 的形式出现。当请求中有正文数据时,Content-Type 应自动添加。我已设置参数:

// Save the profile
var params: [String: AnyObject] = ["indexPhoto": userProfile.indexPhoto,
"dob": df.stringFromDate(userProfile.dob) as NSString,
"identAs": userProfile.identAs]
// Add manually since creating the dictionary all at once is too much for swift to handle
params.updateValue(String(format:"%.2f", userProfile.heightIn), forKey: "heightIn")
params.updateValue(String(format:"%.2f", userProfile.weightLbs), forKey: "weightLbs")
params.updateValue(userProfile.eyes, forKey: "eyes")
params.updateValue(userProfile.hair, forKey: "hair")
...

我可能会遗漏什么吗?在我升级到 Alamofire 2.0 之前,这个调用工作得很好。

最佳答案

也许有不同的方法,但我通过发送空参数而不是 nil 解决了同样的问题。使用 .PUT 时我不使用任何参数,因为该服务器不知道如何对请求和响应进行编码(即使我在 header 内显式设置内容类型,我也会在服务器上收到空白内容类型),所以我的解决方案是发送空参数,如下面的代码所示。希望它对某人有帮助。

var url = https://api.mysite.com/v1/issue/369613/delete

let params = ["":""]

let headers = NetworkConnection.addAuthorizationHeader(token, tokenType: tokenType)
manager.request(.PUT, url, parameters: params, encoding: .JSON, headers: headers)
.responseJSON { response in
if let JSONdata = response.result.value {
print("JSONdata: \(JSONdata)")
}
}

关于swift - Alamofire 2.0 的放置请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32596031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com