一尘不染

如何将Alamofire与自定义标头一起用于POST请求

swift

Alamofire使用自定义标头实现了POST请求,因为我们使用OAuth2,并且必须在标头内的每个请求中发送访问令牌。在这种情况下,我必须使用自定义标头。

HTTP标头字段的访问令牌值Authorization对我不起作用。服务器生成错误,因为带有访问令牌的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)")
    }

阅读 308

收藏
2020-07-07

共1个答案

一尘不染

这是我如何与自定义标头一起使用的示例:

    var 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"
    ]

现在,无论何时发出请求,它都会使用指定的标头。

您的代码已重构:请记住 import 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, response, data, error) -> Void in

            println("REQUEST: \(request)")
            println("RESPONSE: \(response)")
            println("DATA: \(data)")
            println("ERROR: \(error)")
    }

这是请求签名 request(method: Method, URLString: URLStringConvertible>, parameters: [String : AnyObject]?, encoding: ParameterEncoding)

如您所见,您不必在其中传递NSURL,只需传递URL的字符串即可,其余的则由Alamofire负责。

2020-07-07