网络编程03 -- cookie的使用

客户端登录接口中的Cookie

  • 由于HTTP协议是无状态的,客户端需借助cookie来实现跨URL的请求;
  • 实现原理为:客户端登录服务端,服务端下发cookie数据给客户端,客户端的NSURLResponse根据会当前的NSHTTPCookieStorage接受策略自动接收服务端返回的cookie并存储在NSHTTPCookieStorage容器中,我们不需要做任何操作,当我们发送其他网络请求(NSURLRequest)时,我们只需要设置NSURLRequestHTTPShouldHandleCookies属性为YES(默认为YES),NSURLRequest会自动附带cookie的信息发送给服务器;
  • NSHTTPCookieStorage可设置cookieAcceptPolicy属性,定义其接收cookie的策略,总共有三种接收策略,如下所示:
typedef NS_ENUM(NSUInteger, NSHTTPCookieAcceptPolicy) {
    NSHTTPCookieAcceptPolicyAlways,
    NSHTTPCookieAcceptPolicyNever,
    NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain
};
  • NSHTTPCookieAcceptPolicyAlways:永远接收Cookie,这种情况下,NSHTTPCookieStorage会将接收到的cookie 存储在偏好设置中;
  • NSHTTPCookieAcceptPolicyNever:永远不接受Cookie,这种情况下,NSHTTPCookieStorage不会存储cookie到本地;
  • NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain:只接收指定域名的Cookie;
  • NSHTTPCookieStorage的常见Api操作如下所示:
// cookie的接收策略
@property NSHTTPCookieAcceptPolicy cookieAcceptPolicy

// 获取NSHTTPCookieStorage存储的所有cookie
@property (nullable , readonly, copy) NSArray *cookies

// 设置cookie
- (void)setCookie:(NSHTTPCookie *)cookie

// 删除cookie
- (void)deleteCookie:(NSHTTPCookie *)cookie

// 在某个时间点删除cookies
- (void)removeCookiesSinceDate:(NSDate *)date

// 获取指定URL的cookies
- (nullable NSArray *)cookiesForURL:(NSURL *)URL

// 获取指定域名指定URL的cookies
- (void)setCookies:(NSArray *)cookies forURL:(nullable NSURL *)URL mainDocumentURL:(nullable NSURL *)mainDocumentURL
  • NSHTTPCookieStorage容器中存储的cookie数据是NSHTTPCookie实例对象,涉及的Api如下所示:
// 下面两个方法用于对象的创建和初始化 都是通过字典进行键值设置
- (nullable instancetype)initWithProperties:(NSDictionary *)properties;
+ (nullable NSHTTPCookie *)cookieWithProperties:(NSDictionary *)properties;

// 返回Cookie数据中可用于添加HTTP头字段的字典
+ (NSDictionary *)requestHeaderFieldsWithCookies:(NSArray *)cookies;

// 从指定的响应头和URL地址中解析出Cookie数据
+ (NSArray *)cookiesWithResponseHeaderFields:(NSDictionary *)headerFields forURL:(NSURL *)URL;

// Cookie数据中的属性字典
@property (nullable, readonly, copy) NSDictionary *properties;

// 请求响应的版本
@property (readonly) NSUInteger version;

// 请求相应的名称
@property (readonly, copy) NSString *name;

// 请求相应的值
@property (readonly, copy) NSString *value;

// 过期时间
@property (nullable, readonly, copy) NSDate *expiresDate;

// 请求的域名
@property (readonly, copy) NSString *domain;

//请求的路径
@property (readonly, copy) NSString *path;

// 是否是安全传输
@property (readonly, getter=isSecure) BOOL secure;

// 是否只发送HTTP的服务
@property (readonly, getter=isHTTPOnly) BOOL HTTPOnly;

// 响应的文档
@property (nullable, readonly, copy) NSString *comment;

// 相应的文档URL
@property (nullable, readonly, copy) NSURL *commentURL;

// 服务端口列表
@property (nullable, readonly, copy) NSArray *portList;
  • 在客户端当用户推出登录时,我们需要清除NSHTTPCookieStorage容器中存储的关于用户的所有cookie数据;
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
for (NSHTTPCookie *cookie in cookies) {
   [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}

UIWebView中Cookie机制

  • UIWebView在加载HTML网页时,会自动将网页中cookie数据存储到NSHTTPCookieStorage容器中,然后再加载其他的URL网页请求时,请求会自动携带NSHTTPCookieStorage容器中的cookie数据,基本原理与上述的客户端登录接口中的Cookie的原理是一致的;
  • 在同一个App内,多个UIWebView之间共享cookie数据;
UIWebView中cookie的获取与持久化
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *requestUrl = webView.request.URL.absoluteString;
    NSLog(@" requestUrl: %@",requestUrl);
    
    NSMutableArray *cookieArray = [[NSMutableArray alloc] init];
    ///网页加载完成取出cookies
    NSArray *nCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    for (NSHTTPCookie *cookie in nCookies) {
        ///设置原始 cookie
        NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
        [cookieProperties setObject:cookie.name forKey:NSHTTPCookieName];
        [cookieProperties setObject:cookie.value forKey:NSHTTPCookieValue];
        [cookieProperties setObject:cookie.domain forKey:NSHTTPCookieDomain];
        [cookieProperties setObject:cookie.path forKey:NSHTTPCookiePath];
        [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];
        [cookieArray addObject:cookieProperties];
        
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
   ///cookie 持久化 存入本地
   [[NSUserDefaults standardUserDefaults] setObject:cookieArray forKey:@"cookieArray"];
   [[NSUserDefaults standardUserDefaults] synchronize];
}
WKWebView的Cookie机制
  • 在iOS11之前, WKWebView 加载HTML发起的URL请求不会自动带上存储于 NSHTTPCookieStorage 容器中的 Cookie,出现cookie丢失的问题;
  • 在iOS11之后,iOS提供了WKHTTPCookieStore类,其类似于NSHTTPCookieStorage,是一个存储cookie数据的容器,在发起URL请求时,会自动保存网页中的cookie,再加载其他的URL网页请求,会自动携带上cookie数据,但第一次发起URL请求时,依然存在cookie丢失的问题;
第一个问题:在 iOS11之前WKWebView第一次加载HTML时,cookie丢失
  • 在iOS11之前,当WKWebView第一次加载HTML时,由于不会读取NSHTTPCookieStorage中的cookie,导致cookie丢失,需要我们将NSHTTPCookieStorage容器中cookie同步到WKWebView中,实现第一次加载HTML的URL请求中携带上cookie数据;
  • 解决方案一:将NSHTTPCookieStorage容器中的cookie同步到URL请求头参数中,代码实现如下:
- (void)injectCookieInHeaderWithRequest:(NSMutableURLRequest *)request {
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    NSMutableArray *mCookies = [NSMutableArray new];
    for (NSHTTPCookie *cookie in cookies) {
        [mCookies addObject:cookie];
    }
    NSDictionary *headerParams = [NSHTTPCookie requestHeaderFieldsWithCookies:mCookies];
    ///设置请求头 -- 携带NSHTTPCookieStorage容器中cookie数据
    request.allHTTPHeaderFields = headerParams;
}
  • 解决方案二:将NSHTTPCookieStorage中的cookie以JS的形式,注入到WKWebView中,代码实现如下:
- (void)syncCookieToWKWithJSForRequest:(NSMutableURLRequest *)request {
    ///读取NSHTTPCookieStorage中的cookie 拼接成JS字符串
    NSArray *tmp = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    NSMutableString *jscode_Cookie = [@"" mutableCopy];
    [tmp enumerateObjectsUsingBlock:^(NSHTTPCookie * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"%@ = %@",obj.name,obj.value);
        [jscode_Cookie appendString:[NSString stringWithFormat:@"document.cookie = '%@=%@';", obj.name, obj.value]];
    }];
     
    WKUserContentController *userContentController = WKUserContentController.new;
    WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource: jscode_Cookie injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [userContentController addUserScript:cookieScript];
    WKWebViewConfiguration *webViewConfig = WKWebViewConfiguration.new;
    webViewConfig.userContentController = userContentController;
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH) configuration:webViewConfig];
    [self.view addSubview:webView];
}
iOS11之前的跨域重定向的cookie同步问题,主要是针对上面的两种方案的再处理,在,代码如下:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    ///出现跨域时 cookie重新同步 JS方式
    if (![self.currentUrl.host isEqualToString:navigationAction.request.URL.host]) {
        //跨域重定向注入cookieScript
        NSString *strDocumentCookie = [MKCookieManager genDocumentCookieForWKWebview:navigationAction.request.URL];
        WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:strDocumentCookie injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
        [webView.configuration.userContentController  addUserScript:cookieScript];
 
        self.currentUrl = [NSURL URLWithString:navigationAction.request.URL.absoluteString];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    ///出现跨域时 cookie重新同步 请求头参数
    if (![self.currentUrl.host isEqualToString:navigationAction.request.URL.host]) {
        self.currentUrl = [NSURL URLWithString:navigationAction.request.URL.absoluteString];
        NSMutableURLRequest *request = [navigationAction.request mutableCopy];
        NSString *cookieValue = @"session=4342235345345234;token_id=dsfdfdgsgerqereeytrertewqerw=;uid=543234;";
        [request setValue:cookieValue forHTTPHeaderField:@"Cookie"];
        [webView loadRequest:request];
        decisionHandler(WKNavigationActionPolicyCancel);
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

在 iOS11之后WKWebView第一次加载HTML时,cookie丢失
  • 在iOS11之后,当WKWebView第一次加载HTML时,由于不会读取NSHTTPCookieStorage中的cookie,导致cookie丢失,需要我们将NSHTTPCookieStorage容器中cookie同步到WKWebView中,实现第一次加载HTML的URL请求中携带上cookie数据;
  • 解决方案:将NSHTTPCookieStorage容器中的cookie同步到WKHTTPCookieStore中,只要存于WKHTTPCookieStore中的cookie,WKWebView在发起URL请求时都会带上cookie,代码如下:
- (void)syncCookieWithFirstRequest:(NSMutableURLRequest *)request {
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    if (@available(iOS 11.0, *)) {
        WKHTTPCookieStore *cookieStore = self.wkWebView.configuration.websiteDataStore.httpCookieStore;
        for (NSHTTPCookie *cookie in cookies) {
            [cookieStore setCookie:cookie completionHandler:^{
                
            }];
        }
    } 
}
  • 将上述的两种情况合并,即iOS11前后,WKWebView第一次发起URL请求时,将NSHTTPCookieStorage中cookie同步到WKWebView中,代码如下:
///WKWebView第一次发起URL请求时 将NSHTTPCookieStorage中cookie同步到WKWebView中
- (void)syncCookieToWKWithFirstRequest:(NSMutableURLRequest *)request {
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    if (@available(iOS 11.0, *)) {
        WKHTTPCookieStore *cookieStore = self.wkWebView.configuration.websiteDataStore.httpCookieStore;
        for (NSHTTPCookie *cookie in cookies) {
            [cookieStore setCookie:cookie completionHandler:^{
                
            }];
        }
    } else {
        NSMutableArray *mCookies = [NSMutableArray new];
        for (NSHTTPCookie *cookie in cookies) {
            [mCookies addObject:cookie];
        }
        NSDictionary *headerParams = [NSHTTPCookie requestHeaderFieldsWithCookies:mCookies];
        ///设置请求头 -- 携带NSHTTPCookieStorage容器中cookie数据
        request.allHTTPHeaderFields = headerParams;
    }
}

参考文章

iOS 深入浅出 网络编程之 NSHTTPCookie/NSHTTPCookieStorage
iOS UIWebView 和 WKWebView 的 cookie 获取,设置,删除
https://blog.csdn.net/Forever_wj?type=blog

你可能感兴趣的:(网络编程03 -- cookie的使用)