我想通过 Alamofire 4.5 发出 HTTP post 请求。该请求需要一个授权 header (这是一个 Api key )。但是每当我发出请求时,我的服务器都无法检测到 ApiKey
。”
下面是我如何发出 Alamofire 请求
let params : [String : Any] =["param1":param1,"param2":param2]
let headers : HTTPHeaders = ["authorization" : apiKey]
Alamofire.request(MY_URL, method: .post, parameters: params, headers: headers).responseJSON {
response in
switch response.result{
case .success(let result):
//other code here
}
我三次检查了 apiKey
的值,值是正确的,但是发送的请求,我的服务器根本无法检测到 authorization
。
我完全不知道我是否在这里做错了什么,因为我是 Swift 的新手。请提供适当的解决方案。谢谢
编辑:
在我的服务器代码中,我使用 Slim 2
$app->map('/MY_URL','authenticate',function ()use($app){
}
'authenticate' 是扫描 header 中的 authorization: apiKey
的点,所以现在的问题是我的服务器无法获取 apiKey
的值,因此总是提供我在找不到 Api key 时设置的相同错误“Api key 丢失”。
我在 Alamofire Documentation 中尝试了下面的方法, 但结果还是一样。
我尝试了什么:
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
debugPrint(response)
}
我在这里错过了什么?有人请给我一些提示..谢谢。
编辑:
为了更清楚地说明我的意思是授权:apiKey
,我展示了我在Postman
中提出请求的方式。
通常我只是在请求的 Headers 中插入 "authorization": apiKey
但在 Swift 中,web 服务无法获取 apiKey
的值,因此服务器总是返回以下响应:
{
"error": true,
"message": "Api key is missing"
}
最佳答案
我在 Alamofire 4.6.0 上运行良好
let url = "WEB API URL"
let headers = [
"Content-Type":"application/x-www-form-urlencoded",
"authorization" : "apiKey"
]
let configuration = URLSessionConfiguration.default
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
let params : [String : Any] = ["param1":param1,"param2":param2]
Alamofire.request(url, method: .post, parameters: params as? Parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in
if let JSON = response.result.value {
print("JSON: \(JSON)")
}else{
print("Request failed with error: ",response.result.error ?? "Description not available :(")
}
}
关于ios - 如何在 Alamofire 4.5、Swift 4 的 header 中发送 `apikey`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47716495/