2

我正在使用 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")

4

1 回答 1

7

尝试这个 :

     var sessionConfig = URLSessionConfiguration.default
      var authValue: String? = "Bearer \(key)"
     sessionConfig.httpAdditionalHeaders = ["Authorization": authValue ?? <#default value#>]
     var session = URLSession(configuration: sessionConfig, delegate: self as? URLSessionDelegate, delegateQueue: nil)
于 2017-06-28T11:05:18.450 回答