使用Alamofire的授权标头 [英] Authorization header using Alamofire

查看:287
本文介绍了使用Alamofire的授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用将授权密钥放在标头中的API,在Postman中可以正常工作:

I'm working with an API which puts an authorization key in the header, it works fine in Postman:

这是我的代码:

let url = Requests.listCities(withLanguage: .en)
        let headers: HTTPHeaders = [ "Authorization": "pmJAdo5N26WW74kCEy6RRvIdCScFCbAtKc2o0FNy"]
        Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
            .validate(contentType: [MIMEType.JSON])
            .responseJSON {response in
                completion(response)
        }

响应为:

SUCCESS: {
    error = Unauthorized;
    status = failed;
}

我做错了还是授权在请求过程中被省略?

Am I doing it wrong or is the Authorization omitted during the request?

这是请求调试:

$ curl -v \
    -H "Accept-Language: en;q=1.0, ar-US;q=0.9" \
    -H "Authorization: pmJAdo5N26WW74kCEy6RRvIdCScFCbAtKc2o0FNy" \
    -H "User-Agent: skinup/1.0 (appname; build:1; iOS 10.3.1) Alamofire/4.5.0" \
    -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" 


推荐答案

将Alamofire的标头设置为URLRequest。因此,您可以这样做:

You can set the Alamofire's headers into an URLRequest. So you can do this:

    var urlRequest = URLRequest(url: URL(string: "your URL")!)
    urlRequest.httpMethod = HTTPMethod.get.rawValue
    urlRequest = try! URLEncoding.default.encode(urlRequest, with: nil)
    urlRequest.setValue("pmJAdo5N26WW74kCEy6RRvIdCScFCbAtKc2o0FNy", forHTTPHeaderField: "Authorization")

    Alamofire.request(urlRequest).responseJSON(completionHandler: {
        response in

        //code below
        completion(response)
    })

也许它将解决您的问题;)

Maybe It would solve your problem ;)

这篇关于使用Alamofire的授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆