我用Alamofire实现了一个自定义头文件的POST请求,因为我们使用OAuth2,并且我们必须在头部内的每个请求中发送访问令牌。在这种情况下,我必须使用自定义标题。
HTTP头字段授权的访问令牌值对我来说不起作用。由于具有访问令牌的OAuth的头信息不可用,服务器会生成错误。
这是我现在的代码:
let URL = NSURL(string: url + "/server/rest/action") var mutableURLRequest = NSMutableURLRequest(URL: URL!) mutableURLRequest.setValue("Bearer \(accessToken)",forHTTPHeaderField: "Authorization") //this method does not work anymore because it returns an error in the response //Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": "Bearer \(accessToken)"] Alamofire.Manager.sharedInstance .request(.POST,mutableURLRequest,parameters: parameters,encoding: .JSON) .validate() .responseJSON { (request,response,data,error) -> Void in NSLog("REQUEST: \(request)") NSLog("RESPONSE: \(response)") NSLog("DATA: \(data)") NSLog("ERROR: \(error)") }
以下是使用自定义标头的示例:
原文链接:https://www.f2er.com/swift/320604.htmlvar manager = Manager.sharedInstance // Specifying the Headers we need manager.session.configuration.HTTPAdditionalHeaders = [ "Content-Type": "application/x-www-form-urlencoded","Accept": "application/vnd.lichess.v1+json","X-Requested-With": "XMLHttpRequest","User-Agent": "iMchess" ]
现在每当您发出请求时,它将使用指定的标题。
您的代码重构:
记得要进口Alamofire
let aManager = Manager.sharedInstance manager.session.configuration.HTTPAdditionalHeaders = [ "Authorization": "Bearer \(accessToken)" ] let URL = url + "/server/rest/action" request(.POST,URL,encoding: .JSON) .responseJSON { (request,error) -> Void in println("REQUEST: \(request)") println("RESPONSE: \(response)") println("DATA: \(data)") println("ERROR: \(error)") }
这是请求签名请求(方法:方法,URLString:URLStringConvertible>,参数:[String:AnyObject]?encoding:ParameterEncoding)
您可以看到,您不必通过NSURL,只是URL的字符串,Alamofire负责其余的。