我有一个 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 请求:
Best Answer-推荐答案 strong>
尝试改变
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/
|