【问题标题】:Can't send Authorization header with my request无法随我的请求发送授权标头
【发布时间】:2019-05-31 04:58:09
【问题描述】:

我有一个 sylius API 的请求端点,当我通过邮递员使用 application/json 设置内容类型标头和具有确切值 Bearer SampleToken 的授权标头时,它会以预期的响应很好地响应,但是当我尝试设置通过 URLRequest 的请求授权标头它给了我一个响应

{
"error" = "access_denied";
"error_description" = "OAuth2 authentication required";

}

当我通过 charles 监控请求时,我注意到 Authorization 标头已被剥离。我尝试了许多不同的方法来设置授权标头,但没有成功。

func getTotalProducts(page:String){
let urlPath="https://demo.sylius.com/api/v2/taxons"
var request = URLRequest(url:  NSURL(string: urlPath)! as URL)
request.httpMethod = "GET"

request.setValue("Bearer SampleToken", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

Alamofire.request(request)
    .responseJSON { response in
        switch(response.result){
        case .success(let value):
            print(value)
            break
        case .failure(let error):
            print("something went wrong \(error.localizedDescription)")
        }
    }.session.finishTasksAndInvalidate()

}

原始邮递员请求:

【问题讨论】:

    标签: swift http-headers authorization alamofire


    【解决方案1】:

    既然您使用的是 Alamofire,为什么不简化一些事情呢?

    let url = "https://demo.sylius.com/api/v2/taxons"
    
        let headers: HTTPHeaders = [
            "Authorization": "Bearer SampleToken",
            "Accept": "application/json",
            "Content-Type": "application/json"
        ]
    
        Alamofire.request(url, method: .get, encoding: JSONEncoding.default, headers: headers)
            .responseJSON { response in
                switch(response.result){
                case .success(let value):
                    print(value)
                    break
                case .failure(let error):
                    print("something went wrong \(error.localizedDescription)")
                }
            }.session.finishTasksAndInvalidate()
    

    【讨论】:

      猜你喜欢
      • 2020-05-22
      • 2016-06-27
      • 2021-02-10
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 2018-01-15
      相关资源
      最近更新 更多