1
对于屏幕抓取项目我在Swift中使用NSURLSession来阅读HTML页面。但是已经开始失败,因为返回的页面会重定向到一个新的网页,而我的代码并不遵循这一点。如果没有为会话设置委托,我认为重定向会默认工作。但是这两种情况都没有重定向。这里是我的测试项目:NSURLSession不遵循重定向
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSURLSessionTaskDelegate {
@IBOutlet weak var window: NSWindow!
func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) {
completionHandler(request);
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
var url = NSURL(string: "https://banking.dkb.de");
let defaultConfigObject = NSURLSessionConfiguration.defaultSessionConfiguration();
let session = NSURLSession(configuration: defaultConfigObject, delegate: self, delegateQueue: nil);
let task = session.dataTaskWithURL(url!, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
let text = NSString(data: data, encoding: NSUTF8StringEncoding);
// text contains here: <head><meta HTTP-EQUIV="REFRESH" content="0; url=/dkb/"></head>
if var document = NSXMLDocument(data: data, options: Int(NSXMLDocumentTidyHTML), error: nil) {
if let forms = document.nodesForXPath("//form[@name='login']", error: nil) where forms.count > 0 {
let form = forms[0] as! NSXMLNode;
}
}
});
task.resume();
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
我必须做些什么才能使重定向在这里工作?
更新:
在进一步的调查,我发现,它必须与来自服务器的结果做。例如使用https://www.google.com
确实会触发重定向委托。但是,由于任何浏览器都可以处理来自银行地址的重定向,因此必须采取不同的方法来妥善处理该问题,我想了解具体方法。
我希望它有帮助 - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/RequestChanges.html#//apple_ref/doc/uid/TP40009506-SW1 –
有已经阅读过。通过元标记重定向不是以这种方式处理的。 –