我最近升级到了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
作为请求的空白,应该以{{1}}的形式进入。当请求中有正文数据时,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")
...
之前,此通话工作正常。
答案 0 :(得分:0)
也许有不同的方式,但我通过发送空params而不是nil修复了同样的问题。我在使用.PUT时不使用任何参数,因为该服务器不知道如何编码请求和响应(即使我在头文件中明确设置内容类型,我在服务器上收到空白内容类型)所以我的解决方案是发送空的参数,如下面的代码。希望它可以帮到某人。
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)")
}
}