使用Alamofire的授权标头

时间:2017-07-04 14:06:21

标签: ios alamofire

我正在使用一个API,它将一个授权密钥放在标题中,它在Postman中运行正常:

Postman snippet

这是我的代码:

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

我做错了还是在请求期间忽略了Authorization

这是请求调试:

$ 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 个答案:

答案 0 :(得分:1)

您可以将Alamofire的标头设置为URLRequest。所以你可以这样做:

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

也许这会解决你的问题;)