在HTTP请求后保存并发送cookie

时间:2016-11-18 08:15:42

标签: ios swift cookies

我使用URLRequestURLSession的POST请求登录API。自从我收到API的正确回复后,一切似乎都运行良好。

然后我想向同一个API发送一个GET请求,但似乎我已经不再连接了。

对于我所看到的,API正在以其形式在其标题中发送Cookie:

Cookie:PHPSESSID=abc123

我想这个问题来自那个我执行GET请求时没有发送的cookie。

这是我的代码。

ViewController:

    @IBAction func Connection(_ sender: AnyObject) {
    let loginFunc = Login()
    loginFunc.login(username: username.text!, password: password.text!) { jsonString in
           let response = jsonString
           print(response)
    }
    let get = GetRequest()
    get.get(req: "patient/info") { jsonString in
        let response = jsonString
        print(response)
    }
}

Login.swift:

    class Login {
    func login(username: String, password: String, completion: @escaping (String) -> ()) {
        var request = URLRequest(url: URL(string: "http://myurl/web/app_dev.php/login_check")!)
        request.httpMethod = "POST"
        let config = URLSessionConfiguration.default
        let postString = "_username=" + username + "&_password=" + password
        request.httpBody = postString.data(using: .utf8)
        var responseString = ""
        let mysession = URLSession.init(configuration: config)
        let task = mysession.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }

            responseString = String(data: data, encoding: .utf8)!
            let httpResponse = response as! HTTPURLResponse
            let field = httpResponse.allHeaderFields["Cookie"]
            print(field)
            print(type(of: response))
            completion(responseString)
        }
        task.resume()
    }
  }

GetRequest.swift:

    class GetRequest {
    func get(req: String, completion: @escaping (String) -> ()) {
        var request = URLRequest(url: URL(string: "http://myurl/web/app_dev.php/" + req)!)
        request.httpMethod = "GET"
        var responseString = ""
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }

            responseString = String(data: data, encoding: .utf8)!
            print(responseString)
            completion(responseString)
        }
    task.resume()
    }
}

1 个答案:

答案 0 :(得分:-1)

嘿,要发送cookie以及你的ajax请求,请使用。您需要使用withCredentials为true。

$.ajaxSetup({
  dataType: 'json',
  contentType: 'application/json',
  async: true,
  cache: false,
  processData: false,
  crossDomain: true,
  xhrFields: {
    withCredentials: true
  }
});