ios 使用 NSURLSession 设置 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23218242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:59:52  来源:igfitidea点击:

Set cookies with NSURLSession

iossession-cookiesnsurlsession

提问by nilkash

Hi I am developing one Iphone application In which I want to set cookies after server response and use that for another request. My network request looks like.

嗨,我正在开发一个 Iphone 应用程序,我想在其中设置服务器响应后的 cookie,并将其用于另一个请求。我的网络请求看起来像。

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
    NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
    NSLog(@"sttaus code %i", httpResp.statusCode);
    if (error) {
        [self.delegate signinWithError:error];
    }
    else {
        [self.delegate signinWithJson:data];
    }
}] resume];

But I don't know how to set cookies. I know I have to use NSHTTPCookieStoragebut I don't know how to set. And I also want to use that cookies for another request. Is there any one who knows about this? Need help. Thank you.

但我不知道如何设置cookies。我知道我必须使用,NSHTTPCookieStorage但我不知道如何设置。而且我还想将该 cookie 用于另一个请求。有没有人知道这一点?需要帮忙。谢谢你。

See I tried in this way

看我这样试过

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{      
    if(error) {
        [self.delegate signinWithError:error];
    }
    else {
        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;

        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
        NSHTTPCookie *cookie;

        NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];

        NSDictionary* headers = [(NSHTTPURLResponse *)response allHeaderFields];

        for(NSString *key in [headers allKeys]) {
            NSLog(@"%@ ..PPPP ... %@",key ,[headers objectForKey:key]);
            [cookieProperties setObject:[headers objectForKey:key] forKey:key];
        }

        [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];

        cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

        [self.delegate signinWithJson:data];
    }
}] resume];

I am interested in only one header field Set-Cookie SSID=kgu62c0fops35n6qbf12anqlo7; path=/

我只对一个标题字段感兴趣 Set-Cookie SSID=kgu62c0fops35n6qbf12anqlo7; path=/

采纳答案by Rich

You can probably get away with just using the sharedHTTPCookieStoragefor NSHTTPCookieStorage, and then use setCookies:forURL:mainDocumentURL:or the single setCookie:- the latter might be better for your needs.

您可能只需使用sharedHTTPCookieStoragefor NSHTTPCookieStorage,然后使用setCookies:forURL:mainDocumentURL:或 single就可以逃脱setCookie:- 后者可能更适合您的需求。

If this doesn't work you might need to setup the NSURLSessionConfigurationand set the NSHTTPCookieStorage

如果这不起作用,您可能需要设置NSURLSessionConfiguration并设置NSHTTPCookieStorage

The docs don't state it, but the defaultSessionConfigurationmight use the shared store anyway.

文档没有说明,但defaultSessionConfiguration无论如何都可能使用共享存储。

NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
    NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;

    NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:[response URL]];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:cookies forURL:[response URL] mainDocumentURL:nil];

    NSLog(@"sttaus code %i", httpResp.statusCode);
    if (error) {
        [self.delegate signinWithError:error];
    }
    else {
        [self.delegate signinWithJson:data];
    }
}] resume];

回答by Carson

I researched a lot but found one in a website of another language. The solution is to add an empty event handler for session start and end:

我研究了很多,但在另一种语言的网站上找到了一个。解决方案是为会话开始和结束添加一个空的事件处理程序:

protected void Session_Start(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}