OStack程序员社区-中国程序员成长平台

标题: ios - Swift:未设置请求授权 header [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:46
标题: ios - Swift:未设置请求授权 header

我有一个 sylius 的请求端点 API当我使用 application/json 设置内容类型 header 和 exact value Bearer SampleToken header 时通过 postman ,它可以很好地响应预期的响应,但是当我尝试通过 URLRequest 设置请求授权 header 时,它会给我一个响应

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

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

func getTotalProducts(page:String){
    let urlPath="https://demo.sylius.com/api/v2/products"
    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()
}

原始 postman 请求:

enter image description here



Best Answer-推荐答案


尝试改变

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

    request.allHTTPHeaderFields = [
       "Authorization": "Bearer SampleToken",
       "Content-Type": "application/json"
    ]

关于ios - Swift:未设置请求授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53130336/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4