如何使用Cookie发出NSURLSesssion GET请求

How to make a NSURLSesssion GET request with cookies(如何使用Cookie发出NSURLSesssion GET请求)

本文介绍了如何使用Cookie发出NSURLSesssion GET请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Pinterest SDK下载Pinterest Pin的链接(我从服务器返回的示例链接:https://www.pinterest.com/r/pin/186195765822871832/4801566892554728205/77314e40aeb26c0dc412e9cfa82f8dccc401fdb2b9806a3fe17ba8bafdb50510)。

大约5天前,当我尝试访问从Pinterest下载的类似链接时,我的NSURLSesssion中开始出现404个错误。

一位朋友说,他认为Pinterest现在必须使用cookie才能访问该链接。

如何配置我的会话,以便可以使用Cookie并从Pinterest获得200响应?

更新代码:

import UIKit
import PlaygroundSupport


var url = URL(string: "https://www.pinterest.com/r/pin/186195765822871832/4801566892554728205/77314e40aeb26c0dc412e9cfa82f8dccc401fdb2b9806a3fe17ba8bafdb50510")

var getSourceURLFromPinterest: URLSessionDataTask? = nil
let sessionConfig: URLSessionConfiguration = URLSessionConfiguration.default

sessionConfig.timeoutIntervalForRequest = 30.0
sessionConfig.timeoutIntervalForResource = 30.0

let cookieJar = HTTPCookieStorage.shared
let cookieHeaderField = ["Set-Cookie": "key=value, key2=value2"]
let cookies = HTTPCookie.cookies(withResponseHeaderFields: cookieHeaderField, for: url!)
HTTPCookieStorage.shared.setCookies(cookies, for: url, mainDocumentURL: url)

let session = URLSession(configuration: sessionConfig)
getSourceURLFromPinterest = session.dataTask(with: url! as URL) { (data: Data?, response: URLResponse?, error: Error?) -> Void in

        if error != nil {
        print("error is (error)")
    }
    if response == nil {
    print("no response")

    } else if let _ = data {

        //Config Request
        let request = NSMutableURLRequest(
            url: (response?.url)!,
            cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
            timeoutInterval: 30.0)
        request.httpMethod = "HEAD"

        var statusCode = Int()
        let session = URLSession.shared
        let checkURLForResponse = session.dataTask(with: request as URLRequest) {urlData, myResponse, responseError in
            if let httpResponse = myResponse as? HTTPURLResponse {
                 statusCode = httpResponse.statusCode
                               switch statusCode {
                case  _ where statusCode < 500 && statusCode > 299 && statusCode != 405: //whitelisted 405 to exclude Amazon.com false errors
                    print("status code (statusCode) for (url)")
                default:
                    break;
                }
            } else {  print("***NO httpResponse for (url)") }
        }
        checkURLForResponse.resume()
    }
}
 getSourceURLFromPinterest!.resume()

PlaygroundPage.current.needsIndefiniteExecution = true

推荐答案

其他答案一般都可以,但对我来说,这就是我为了从Pinterest的服务器获得响应而对请求进行编码的方式。请注意,我认为我正在做的具体操作与Pinterest服务器中可能存在的错误有关,请参阅:https://github.com/pinterest/ios-pdk/issues/124

我注释掉了我的个人Pinterest会话ID

var cookieSession = String()
var cookieCSRFToken = String()

var myWebServiceUrl = URL(string: "https://www.pinterest.com/r/pin/186195765821344905/4801566892554728205/a9bb098fcbd6b73c4f38a127caca17491dafc57135e9bbf6a0fdd61eab4ba885")

let requestOne = URLRequest(url: myWebServiceUrl!)
let sessionOne = URLSession.shared

let taskOne = sessionOne.dataTask(with: requestOne, completionHandler: { (data, response, error) in
    if let error = error {
        print("ERROR: (error)")
    }
    else {
        print("RESPONSE: (response)")

        if let data = data, let dataString = String(data: data, encoding: .utf8) {
            print("DATA: " + dataString)
        } // end: if

        var cookies:[HTTPCookie] = HTTPCookieStorage.shared.cookies! as [HTTPCookie]
        print("Cookies Count = (cookies.count)")
        for cookie:HTTPCookie in cookies as [HTTPCookie] {

            // Get the _pinterest_sess ID
            if cookie.name as String == "_pinterest_sess" {
                //var cookieValue : String = "CookieName=" + cookie.value as String
                cookieSession = cookie.value as String
                print(cookieSession)
            }

            // Get the csrftoken
            if cookie.name as String == "csrftoken" {
                cookieCSRFToken = cookie.value
                print(cookieCSRFToken)
            }
        } // end: for

    } // end: if
})
taskOne.resume()

var requestTwo = URLRequest(url: myWebServiceUrl!)

cookieSession = "XXXXXXXX"

cookieCSRFToken = "JHDylCCKKNToE4VXgofq1ad3hg06uKKl"

var cookieRequest = "_auth=1; _b="AR4XTkMmqo9JKradOZyuMoSWcMdsBMuBHHIM21wj2RPInwdkbl2yuy56yQR4iqxJ+N4="; _pinterest_pfob=disabled; _pinterest_sess="" + cookieSession + ""; csrftoken=" + cookieCSRFToken as String


requestTwo.setValue(cookieRequest as String, forHTTPHeaderField: "Cookie")


let taskTwo = sessionOne.dataTask(with: requestTwo, completionHandler: { (data, response, error) in
    if let error = error {
        print("ERROR: (error)")
    }
    else {
        print("RESPONSE: (response)")

    } // end: if
})
taskTwo.resume()

PlaygroundPage.current.needsIndefiniteExecution = true

这篇关于如何使用Cookie发出NSURLSesssion GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何使用Cookie发出NSURLSesssion GET请求

基础教程推荐