美文网首页
OC设置cookie

OC设置cookie

作者: 半夏半暖半倾城灬 | 来源:发表于2018-03-07 15:03 被阅读0次

    移动端接入H5类型的业务常常需要给H5网页传递一些公共信息,如登录的用户信息,常用的解决方案就是通过cookie共享(有安全需要的话需加密)

    //cookie设置

    + (void)setUserAndCookieWithRequest:(NSMutableURLRequest *)request

    {

        if(![UserInfoModel defaultUser] && request.URL.host.length>0)    {

            NSString *userInfo = [UserInfoModel defaultUser];

            NSMutableDictionary * cookieProperties = [NSMutableDictionary dictionary];

            [cookieProperties setObject:@"userInfo" forKey:NSHTTPCookieName];

            [cookieProperties setObject:userInfo forKey:NSHTTPCookieValue];

            [cookieProperties setObject:request.URL.host forKey:NSHTTPCookieDomain];

            [cookieProperties setObject:request.URL.host forKey:NSHTTPCookieOriginURL];

            [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];

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

    //初始化cookie

            NSHTTPCookie * cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];

    //添加cookie到NSHTTPCookieStorage中

            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

    //设置cookie到请求头

            NSArray * cookies = @[cookie];

            NSDictionary * cookieHeaderDic = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];

            [request setValue:[cookieHeaderDic objectForKey:@"Cookie"] forHTTPHeaderField:@"Cookie"];

        }

    }

    相关文章

      网友评论

          本文标题:OC设置cookie

          本文链接:https://www.haomeiwen.com/subject/loyjfftx.html