gpt4 book ai didi

swift - 无法随我的请求发送授权 header

转载 作者:行者123 更新时间:2023-11-28 11:39:38 27 4
gpt4 key购买 nike

我有一个 sylius 的请求端点 API当我通过 postman 将内容类型 header 设置为 application/json 并将授权 header 设置为具有确切值 Bearer SampleToken 时,它可以很好地响应预期的响应,但是当我尝试通过 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/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()

原始 postman 请求:

最佳答案

既然您使用的是 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()

关于swift - 无法随我的请求发送授权 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54042016/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com