从POST调用URLSession中获取内容

时间:2018-09-25 18:26:15

标签: swift nsurlsession nsurl urlsession

我正在尝试从此POST调用中提取Cookie,以用于其他调用。

我在这里有一个POST呼叫的URLSession响应:

<NSHTTPURLResponse: 0x600000418120> { URL: https://example.com:443/Auth/ } { Status Code: 200, Headers {
Accept =     (
    "*/*"
);
"Accept-Encoding" =     (
    "br, gzip, deflate"
);
"Accept-Language" =     (
    "en-us"
);
Authorization =     (
    "Basic keyHere=="
);
"Content-Encoding" =     (
    gzip
);
"Content-Type" =     (
    "application/json"
);
Date =     (
    "Tue, 25 Sep 2018 18:17:38 GMT"
);
Host =     (
    "example.com:443"
);
"SMSESSION-Idle-Expire" =     (
    "Tue, 25-Sep-2018 20:17:38 GMT"
);
"SMSESSION-Session-Expire" =     (
    "Wed, 26-Sep-2018 04:17:38 GMT"
);
"Set-Cookie" =     (
    "SMSESSION=sessionKeyHere==;Domain=example.com;Path=/"
);
"Transfer-Encoding" =     (
    Identity
);
"User-Agent" =     (
    "Web%20Service%20Test/1 CFNetwork/974.2.1 Darwin/18.0.0"
);
"X-Forwarded-For" =     (
    "11.111.11.11"
);
} }

如何从此处拉Set-Cookie SMSESSION键?有正确的方法吗?还是我只是解析此响应并从那里拉出密钥?

这是我的功能:

func test() {
    let username = "myUsername"
    let password = "myPassword"
    let loginString = String(format: "%@:%@", username, password)
    let loginData = loginString.data(using: String.Encoding.utf8)!
    let base64LoginString = loginData.base64EncodedString()

    let url = URL(string: "https://example.com:443/Auth/")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print(error)
            }
        }
    }.resume()
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

谢谢@Cristik。

let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
    if let response = response {
        let httpResponse = response as! HTTPURLResponse // HTTPURLResponse is a subclass of URLResponse
        print(httpResponse.allHeaderFields["Set-Cookie"] ?? "") // Cookie Value
    }
    if let data = data {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: [])
            print(json)
        } catch {
            print(error)
        }
    }
}.resume()