简体   繁体   English

Swift中等效的Python发布请求

[英]Python post request equivalent in Swift

I have a small script written in python and works fine so i want to implement the same thing in my swift app but could not find a way 我有一个用python编写的小脚本,工作正常,所以我想在我的swift应用中实现相同的功能,但找不到方法

here is my python code: 这是我的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)

So basically i receive 2 text infos from the script (someinfo and someinfo2) and in swift app i need to print them on labels. 所以基本上我从脚本(someinfo和someinfo2)接收2个文本信息,在Swift应用程序中,我需要将它们打印在标签上。

Thank you 谢谢

Use a third-party framework like Alamofire: 使用第三方框架,例如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)
        }
    }

Use only Foundation (ie Apple-provided) classes: 仅使用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()

Notes 笔记

  • Since your request is transported over unsecured HTTP, you may need to set App Transport Security to allow it. 由于您的请求是通过不安全的HTTP传输的,因此您可能需要将App Transport Security设置为允许它。
  • You can't use Alamofire in a console application, or in a playground. 您不能在控制台应用程序或游乐场中使用Alamofire。
  • Both methods execute asynchronously . 这两种方法都是异步执行的。 You must keep the main queue going while waiting for the response. 您必须在等待响应的同时保持主队列继续前进。 In a GUI application, the run loop will keep your app going so it's not a concern. 在GUI应用程序中,运行循环将使您的应用程序继续运行,因此无需担心。 For a console application, you can pause the main queue by calling sleep(secs) or use Grand Central Dispatch to wait for the request. 对于控制台应用程序,您可以通过调用sleep(secs)暂停主队列,或使用Grand Central Dispatch等待请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM