Authorization header using Alamofire

微笑、不失礼 提交于 2020-01-07 06:40:30

问题


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

And it's my code:

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)
        }

The response is:

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

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

This is the request debug:

$ 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" 

回答1:


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 ;)



来源:https://stackoverflow.com/questions/44908117/authorization-header-using-alamofire

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!