大佬教程收集整理的这篇文章主要介绍了ios – 如何在URLSession的HTTP头中为’Authorization’设置’Token xxxxxxxxxx’,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
现在,我正在做以下事情.
var getrequest = URLrequest(url: url) getrequest.addValue("Token xxxxxxxx",forhttpHeaderField: "Authorization")
这有时会起作用,有时候会在发出请求时剥离标题字段授权.我使用Charles代理检查了这个.
作为解决方案,许多人建议对URLSession使用didReceiveAuthenticationChALLENge委托方法.
在这里,您需要传递URLSession.AuthChALLENgeDisposition实例以告知您希望如何响应挑战,并传递URLCredential实例以传递凭据以响应身份验证质询.
@R_849_6618@做,如果我可以创建一个URLCredential实例,它将为头字段授权添加Token xxxxxxxx.
PS – 此问题中提到的所有代码都在Swift 3中.
This question询问类似于我的东西.但是,那里给出的答案对我不起作用.并且,在有关Apple不允许添加授权标题的问题下提出的一些问题没有得到答复.
编辑:
发布相关代码.
var getrequest = URLrequest(url: url) getrequest.httpR_160_11845@ethod = "GET" getrequest.addValue("application/json",forhttpHeaderField: "Content-Type") getrequest.addValue("application/json",forhttpHeaderField: "Accept") let token = DataProvider.sharedInstance.token getrequest.addValue("Token \(token)",forhttpHeaderField: "Authorization") let getTask = URLSession.shared.dataTask(with: getrequest) { (data,response,error) in if let data = data { print("--------GET requEST RESPONSE START--------") print("CODE: \((response as? httpURLResponsE)?.statusCode ?? 0)") print("Response Data:") print(String(data: data,encoding: .utf8) ?? "") print("--------GET requEST RESPONSE END--------") } } getTask.resume()
在这里,我可以确认“授权”的标题字段已添加到请求的标题字典中.
但是,当我检查哪些请求命中服务器时,“授权”的标题字段将丢失.有什么想法吗?
服务器正在发回301重定向响应. URLSession会自动跟随重定向,但也会删除Authorization标头.这可能是由于授权的“特殊状态”.根据URLSessionConfiguration的documentation:
如果需要Authorization标头,请从URLSessionTaskDelegate实现urlSession(_:task:willPerformhttpRedirection:newrequest:completionHandler :).该方法在重定向上传递新请求,允许您添加回头.
例如
class APIClient: URLSessionTaskDelegate { let session: URLSession! initializeSession() { // Create a new session with APIClient as the delegate session = URLSession(configuration: URLSessionConfiguration.default,delegate: self,delegateQueue: nil) } // Perform the request func fetchRecords(handler: () => void) { var request = URLrequest(url: URL(String: "http://127.0.0.1:8000/api/employee/records")!) request.SETVALue(retrieveToken(),forhttpHeaderField: "Authorization") session.dataTask(with: request,completionHandler: handler).resume() } // Implement URLSessionTaskDelegate's http Redirection method func urlSession(_ session: URLSession,task: URLSessionTask,willPerformhttpRedirection response: httpURLResponse,newrequest request: URLrequest,completionHandler: @escaping (URLrequest?) -> Void) { // Create a mutable copy of the new request,add the header,call completionHandler var newrequest = request newrequest.addValue(retrieveToken(),forhttpHeaderField: "Authorization") completionHandler(newrequest) } }
重要的提示!
以上是大佬教程为你收集整理的ios – 如何在URLSession的HTTP头中为’Authorization’设置’Token xxxxxxxxxx’全部内容,希望文章能够帮你解决ios – 如何在URLSession的HTTP头中为’Authorization’设置’Token xxxxxxxxxx’所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。