我正在使用 urlsession 在标头中发送不记名令牌,但我总是得到未经授权的结果。我看过服务器日志。我在那里得到身体,但不是标题。
let key = UserDefaults.standard.object(forKey: "loginKey") as! String
print(key)
let url = NSURL(string: baseurl+"***")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "GET"
request.addValue("Bearer " + key, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request as URLRequest)
{(data,response,error) -> Void in
if error != nil
{
print(error?.localizedDescription as Any)
return
}
do
{
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
print(json)
}
catch let error as NSError
{
print(error.localizedDescription)
}
}
task.resume()
我也试过request.setValue("Bearer " + key, forHTTPHeaderField: "Authorization")