当我使用application / json设置内容类型标头,并通过邮递员将确切类型的值Bearer SampleToken设置为Authorization标头时,我有一个sylius API的请求端点,它可以很好地响应预期的响应,但是当我尝试通过URLRequest设置请求授权标头,它会给我一个响应
{
"error" = "access_denied";
"error_description" = "OAuth2 authentication required";
}
当我通过查尔斯监视请求时,我注意到授权标头被剥夺了。我尝试了多种方法来设置授权标头,但没有运气。
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()
}
原始邮递员请求:
答案 0 :(得分:2)
既然您使用的是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()