iOS-HTTP协议使用cookie

1、平时浏览访问一个网站时,NSURLRequest都会帮你主动记录下来你访问的站点设置的cookie,当你下次再访问这个站点时,NSURLRequest会拿着上次保存下来了的cookie继续去请求。之前以为手机是不存在cookie的,但是看了一些博客文章,发现其实也能输出cookie的。

//  1.创建一个网络路径
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    // 2.创建一个网络请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                             cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                         timeoutInterval:3];
    // 3.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    // 4.根据会话对象,创建一个Task任务:
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        NSLog(@"从服务器获取到数据");
//        
//        /*
//         对从服务器获取到的数据data进行相应的处理:
//         */
//        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
        
    }];
    
    // 5.最后一步,执行任务(resume也是继续执行):
    [sessionDataTask resume];
    
    //输出cookie
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [cookieJar cookies]) {
        NSLog(@"%@", cookie);
    }

 

 

最后会看到控制台输出的cookie内容如下:

 

2016-06-15 20:34:08.017 cookie[1099:37861] 
2016-06-15 20:34:08.019 cookie[1099:37861] 
2016-06-15 20:34:08.019 cookie[1099:37861] 


2、清空cookie代码

 

 

NSHTTPCookieStorage *cookie = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *_tmpArray = [NSArray arrayWithArray:[cookie cookies]];
    for (id obj in _tmpArray) {
        [cookieJar deleteCookie:obj];
    }


3、设置cookie代码

 

 

NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
    [cookieProperties setObject:@"username" forKey:NSHTTPCookieName];
    [cookieProperties setObject:@"ming" forKey:NSHTTPCookieValue];
    [cookieProperties setObject:@"http://write.blog.csdn.net/postlist" forKey:NSHTTPCookieDomain];
    [cookieProperties setObject:@"http://write.blog.csdn.net/postlist" forKey:NSHTTPCookieOriginURL];
    [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
    [cookieProperties setObject:@"1" forKey:NSHTTPCookieVersion];
    
    NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    NSLog(@"%@", cookie);

打印输出如下:

 

 

 

 

 

 

 


 

 

你可能感兴趣的:(iOS-HTTP协议使用cookie)