如何使用Alamofire和POST请求的自定义标头

时间:2015-02-15 13:49:06

标签: swift post header afnetworking alamofire

我使用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)")
    }

4 个答案:

答案 0 :(得分:43)

以下是我如何将其与自定义标头一起使用的示例:

    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负责其余部分。

答案 1 :(得分:4)

有一个简单的解决方案,可以通过单个Alamofire请求为Swift 3和Alamofire 4.0发送参数和标题

    let url = "myURL"
    let parameters: Parameters = [
        "param1": "hello",
        "param2": "world"
    ]
    let headers = [
        "x-access-token": "myToken",
    ]

    Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
        if response.result.isFailure {
            //In case of failure
        }else {
            //in case of success
        }
    }

答案 2 :(得分:0)

let headers: HTTPHeaders = [
        "Cookie": UserDefaultsUtil.getString(param: Constants.COOKIE),
        "Accept": "application/json"
    ]

Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
        .responseObject { (response: DataResponse<Any>) in
            if response.result.isSuccess {

            }
            else {

            }
    }

答案 3 :(得分:0)

从Alamofire 5.0.0开始,您可以使用类型HTTPHeader的集合添加自定义HTTP标头。因此,要添加自定义用户代理标头,您可以按照以下步骤操作: urlRequest.headers.add(.userAgent("Custom User Agent Here"))