移动端接入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"];
}
}
网友评论