【发布时间】:2017-12-17 14:05:22
【问题描述】:
我想在 Alamofire 的标头中将 apiKey 发送到我的 Web 服务。但是无论我测试多少次,我仍然无法在我的 Web 服务中获得 apiKey 的值。
我的网络服务总是返回这个错误,因为无法在标题中获取apiKey。
{
"error": true,
"message": "Api key is missing"
}
这就是我提出请求的方式,我认为我没有做错任何事情,但是网络服务仍然无法获取apiKey的值。
let My_URL = "My_url"
let params : [String : Any]=["param1":value1,"param2":value2]
let headers : HTTPHeaders = [
"Content-Type":"application/x-www-form-urlencoded",
"authorization" : apiKey //<--this is the value I need to
get in header of web service
]
Alamofire.request(MY_URL,method: .post ,parameters : params ,headers:headers).responseJSON {
response in
debugPrint(response)
}
我的网络服务目前为安卓和网络版本提供服务。两者都运行良好,但我真的不知道为什么标题中的ApiKey 无法从网络服务中获取它。
完全不知道出了什么问题..有人请帮忙!!!!
编辑
我在这里附上debugPrint的结果,请看一下,让我知道是什么问题,我怀疑问题是由下面结果中的“授权”标签引起的,“授权”字段不是我设置的字段和值也不是我想要的值。
但是为什么会这样呢?以及如何解决这个问题?
[Response]: <NSHTTPURLResponse: 0x60c00003d4c0> { URL: http://My_URL} { Status Code: 400, Headers {
"Access-Control-Allow-Headers" = (
Authorization
);
"Access-Control-Allow-Methods" = (
"GET, POST, PUT, DELETE, OPTIONS"
);
"Access-Control-Allow-Origin" = (
"*"
);
Authorization = ( // <--why this authorization appear
16ebe49c51039ddfbb09e5df8519e755 //this is not the value I set
);
Connection = (
close
);
"Content-Length" = (
45
);
"Content-Type" = (
"application/json"
);
Date = (
"Sun, 14 Dec 2017 14:20:59 GMT"
);
Server = (
"Apach(Ubuntu)"
);
"X-Powered-By" = (
"PHP/5.5.9-1"
);
} }
编辑: 为了解决上述问题,我阅读了以下问题
iOS Alamofire Incorrect Authorization Header
How to disable the URLCache completely with Alamofire
因此,我将我的请求修改如下,但问题还是一样,debugPrint的结果还是和上面一样。
let configuration = URLSessionConfiguration.default
configuration.urlCache = nil
let sessionManager = Alamofire.SessionManager(configuration: configuration)
let params : [String : Any]=["param1":value1,"param2":value2]
let headers : HTTPHeaders = [
"Content-Type":"application/x-www-form-urlencoded",
"authorization" : apiKey //<--this is the value I need to
get in header of web service
]
sessionManager.request(MY_URL,method: .post ,parameters : params ,headers:headers).responseJSON {
response in
debugPrint(response)
}.session.finishTasksAndInvalidate()
【问题讨论】:
-
可能要发送的 API 密钥是一个空字符串。或者你有错误的标题键。而不是
authorization,它可能是Authorization或API-Key或其他。 -
但是我在控制台打印出
apiKey的值,这个值是正确的,这个问题真的不知道 -
我的
webservice真的在找authorization的钥匙 -
可以在 debugPrint 中设置断点吗?然后,跟踪函数链。
-
我已经在我的问题中附上了
debugPrint结果@mownier,请看一下
标签: ios web-services alamofire swift4