NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:DOCTORAGREEMENT]];
NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:@"cookie111"];
if([cookiesdata length]) {
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
// NSHTTPCookie *cookie;
// for (cookie in cookies) {
// [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
// }
NSDictionary *headers=[NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[request setValue:[headers objectForKey:@"Cookie"] forHTTPHeaderField:@"Cookie"];
}
[ loadRequest:request];
[ setDelegate:self];
在使用UIWebView访问网站时,经常遇到的一个问题是需要登录。比如访问新浪微博,或者访问某个个人账号,但是需要直接访问url,却会被重定向到登录页进行登录。
那么真正的浏览器是如何做到的直接登录?一般来说,答案都是cookies。在你第一次登录时,网站设置了cookie,浏览器保存这些携带了登录信息的cookies,以后就可以直接登录。
所以我们要做的就是在url request中带上cookies。NSMutableURLRequest中提供了- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field 方法。可以用来设置Http request header中的各个属性。
所以,比如我们要设置usrId和token两个cookie。
//set user id to cookie
NSDictionary *dictCookieUId = [NSDictionarydictionaryWithObjectsAndKeys:@"userId", NSHTTPCookieName,
userId, NSHTTPCookieValue,
@"/", NSHTTPCookiePath,
@"t", NSHTTPCookieDomain,
nil];
NSHTTPCookie *cookieUserId = [NSHTTPCookie cookieWithProperties:dictCookieUId];
//set token to cookie
NSDictionary *dictCookiePToken = [NSDictionarydictionaryWithObjectsAndKeys:@"token", NSHTTPCookieName,
token, NSHTTPCookieValue,
@"/", NSHTTPCookiePath,
@"t, NSHTTPCookieDomain,
nil];
NSHTTPCookie *cookiePassToken = [NSHTTPCookie cookieWithProperties:dictCookiePToken];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURLURLWithString:strUrl]];
// set cookies
NSArray *arrCookies = [NSArray arrayWithObjects: cookieUserId, cookiePassToken, nil];
NSDictionary *dictCookies = [NSHTTPCookie requestHeaderFieldsWithCookies:arrCookies];
[request setValue: [dictCookies objectForKey:@"Cookie"] forHTTPHeaderField: @"Cookie"];
return request;
生成cookie的方法是先将cookie的各个property作为键值对生成dictionary,然后调用cookieWIthProperties生成cookie。将生成的cookie放到array中,使用NSHttpCookie的reqeustHeaderFieldsWithCookies方法拼接成合法的http header field。最后set到request中即可。
同样的方法,还可以设置很多http header中的field。