Swift 3 - 如何从URL数据请求提交HTTP表单

时间:2017-06-02 20:17:32

标签: javascript html ios swift3 httpwebrequest

我有点困惑在这一点上做什么。到目前为止,我已经建立了与我想要提交登录表单的网站的连接。当我访问该网站时,它需要一个用户名和密码,然后您可以登录该网站的登录版本。该站点的源代码包含用于输入文本的占位符。占位符的字符串存储为变量。我假设我需要在返回的http数据中搜索它。登录页面中的数据成功返回,打印输出包含这些占位符。我通过文本字段从用户那里获得用户名和密码,但我如何告诉网站"插入"这些用户值作为站点字段并提交表单(基本上按"登录")以便访问该网站的登录版本?当我查看我正在使用的网站的来源时,代码是使用JavaScript。这需要jQuery或JSON解析(GET / POST请求)还是我尝试了错误的东西?

import UIKit

class ViewController: UIViewController {
    final var USERNAME_FIELD = "ctl00$ContentPlaceHolder$Username"
    final var PASSWORD_FIELD = "ctl00$ContentPlaceHolder$Password"

    @IBOutlet weak var gobuttom: UIButton!

    @IBOutlet weak var passField: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        gobuttom.isEnabled = true

        data_request("https://example.com")


    }


    func data_request(_ url:String)
    {
        let url:NSURL = NSURL(string: url)!
        let session = URLSession.shared

        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"

        let paramString = "data=test"
        request.httpBody = paramString.data(using: String.Encoding.utf8)

        let task = session.dataTask(with: request as URLRequest) {
            (
            data, response, error) in

            guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
                print("error")
                return
            }

            if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
            {
                print(dataString)
            }
        }

        task.resume()

    }



    @IBOutlet weak var usernameField: UITextField!

    @IBAction func usernameChanged(_ sender: Any) {
        print("textfield : \(String(describing: usernameField.text))")

        gobuttom.isEnabled = true
    }



    @IBAction func goPressed(_ sender: Any) {

        if(usernameField.text != "" && passField.text != ""){
            print("OK")
        }

    }
}

1 个答案:

答案 0 :(得分:0)

Swift中的Http报废相当复杂。除非您经常使用Web开发,否则没有太多关于如何操作的信息。这是一个关于快速抓取的精彩教程:https://www.youtube.com/watch?v=gscuaUSkxnI