ios - 如何在 Alamofire 4.5、Swift 4 的 header 中发送 `apikey`?

标签 ios alamofire swift4

我想通过 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

enter image description here

但在 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/

相关文章:

ios - 尝试下载文件时 Swift Alamofire 出错

ios - 从 Swift 4 中的 UICollectionView 获取单元格图像

ios - 请求完成处理程序 fatal error : unexpectedly found nil while unwrapping an optional value exception

ios - 类似类型: Cannot specialize a non-generic definition

ios - 由于未捕获的异常 'NSInternalInconsistencyException' 而终止应用程序,原因 : 'Could not load NIB in bundle:

ios - ViewController 的 subview 的 IBOutlets 在 Storyboard 的 viewDidLoad 中为 nil

swift - 在 Swift 中听标准输入

ios - 仅存储在数组中的最后一个图像在表格 View 中显示

ios - Alamofire 不想在查询中接受我的参数 - 它在调用中说额外的参数

ios - Alamofire 4 请求返回 NSArray,无法弄清楚如何在 Swift 3 中使用 SwiftyJSON 进行解析