Python post请求等效于Swift

时间:2016-03-15 08:49:16

标签: python swift http http-post

我有一个用python编写的小脚本并且工作正常所以我想在我的swift应用程序中实现相同的东西但是找不到方法

这是我的python代码:

payload = {'login': 'Submit', 'username': 'username', 'password': 'password', 'redirect': 'iph.php'}
with session() as c:
    c.post('http://mywebsite.com/iph.php', data=payload)
    response = c.get('http://mywebsite.com/mobile.php?page=profile')
    tree = html.fromstring(response.content)
    males = tree.xpath('//td[@id="someinfo"]/text()')
    females = tree.xpath('//td[@id="someinfo2"]/text()')
    print(response.headers)
    print(response.text)

所以基本上我从脚本(someinfo和someinfo2)收到2个文本信息,在swift应用程序中我需要在标签上打印它们。

谢谢

1 个答案:

答案 0 :(得分:2)

使用像Alamofire这样的第三方框架:

let payload = ["login": "Submit", "username": "username", "password": "password", "redirect": "iph.php"]

Alamofire.request(.POST, "http://mywebsite.com/iph.php", parameters: payload)
    .response { request, response, data, error in
        guard let data = data else {
            fatalError("No data returned")
        }
        do {
            let html = try NSXMLDocument(data: data, options: NSXMLDocumentTidyHTML)
            let root = html.rootElement()!
            let males = try root.nodesForXPath("//td[@id='someinfo']/text()")
            let females = try root.nodesForXPath("//td[@id='someinfo2']/text()")
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }

仅使用Foundation(即Apple提供的)类:

let payload = ["login": "Submit", "username": "username", "password": "password", "redirect": "iph.php"]
let request = NSMutableURLRequest(URL: NSURL(string: "http://mywebsite.com/iph.php")!)
request.HTTPMethod = "POST"
request.HTTPBody = NSKeyedArchiver.archivedDataWithRootObject(payload)

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithRequest(request) { data, response, error in
    guard let data = data else {
        fatalError("No data returned")
    }
    do {
        let html = try NSXMLDocument(data: data, options: NSXMLDocumentTidyHTML)
        let root = html.rootElement()!
        let males = try root.nodesForXPath("//td[@id='someinfo']/text()")
        let females = try root.nodesForXPath("//td[@id='someinfo2']/text()")
    } catch let error as NSError {
        print(error.localizedDescription)
    }
}

task.resume()

注释

  • 由于您的请求是通过不安全的HTTP传输的,因此您可能需要设置App Transport Security以允许它。
  • 您无法在控制台应用程序或游乐场中使用Alamofire。
  • 两种方法都异步执行 。您必须在等待响应时保持主队列的运行。在GUI应用程序中,运行循环将保持您的应用程序运行,因此它不是一个问题。对于控制台应用程序,您可以通过调用sleep(secs)暂停主队列,或使用Grand Central Dispatch等待请求。