NSMutableURLRequest
中的标题字段存在问题,当我向HTTPHeaderField添加密钥“authorization”时,确实每隔一个请求都无法执行。
如果失败,我在解析响应时收到NSJSONSerialization
(代码= 3840)的错误,而在服务器日志中,我没有任何有关传入连接的信息。
我的要求是:
let url:NSURL = NSURL(string: "http://my/end/point")!
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let key = prefs.valueForKey("accessToken") as! String
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("key: (\(key))", forHTTPHeaderField: "Authorization")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { urlData, response, error in
if(urlData == nil){
print("\(error)")
}else {
do{
let serialization = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers )
self.jsonData = serialization as? NSDictionary
let success:NSInteger = self.jsonData!.valueForKey("success") as! NSInteger
if(success == 1){
[...]
} else {
print("\(error)")
print("\( self.jsonData!)")
}
}catch{
print("error with jsonSerialization: \(error)")
}
}
}
task.resume()
任何人都知道我的要求有什么问题吗?
编辑:
如果我删除request.addValue("key: (\(key))", forHTTPHeaderField: "Authorization")
然后一切正常,我会收到来自serwer的回复