IOS UIWebView添加Cookie值请求
Posted
技术标签:
【中文标题】IOS UIWebView添加Cookie值请求【英文标题】:IOS UIWebView add Cookie value to request 【发布时间】:2016-04-12 15:15:59 【问题描述】:Xcode 新手,我想将一个页面加载到 UIWebView 中,但要为请求设置一个 cookie。我可以 NSLog cookie 值,所以我知道它已设置。
这是我目前正在做的事情:
-(IBAction)displayRedZones:(id)sender
NSLog(@"red zones");
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(25/100 * (float)self.view.bounds.size.width, 25/100 * (float)self.view.bounds.size.height, (float)self.view.bounds.size.width / 2, (float)self.view.bounds.size.height / 2)];
NSString* combinedString = [self.urlToLoad stringByAppendingString:@"/redzone"];
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: combinedString] cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 1];
[request setHTTPShouldHandleCookies:YES];
webView.scalesPageToFit = YES;
webView.delegate = self;
[self addCookies:cookies forRequest:request];
[webView loadRequest: request];
[self.view addSubview:webView];
- (void)addCookies:(NSArray *)cookies forRequest:(NSMutableURLRequest *)request
NSString *cookieHeader = nil;
NSString* cookieValue = [@"CAKEphp" stringByAppendingString:self.cookieValue];
[request setValue:cookieHeader forHTTPHeaderField:@"Cookie"];
【问题讨论】:
【参考方案1】:我通过执行以下操作解决了这个问题:
-(IBAction)displayRedZones:(id)sender
NSLog(@"red zones");
// Create a web view that fills the entire window, minus the toolbar height
UIWebView *webView = [[UIWebView alloc]
initWithFrame:CGRectMake(0, 0, (float)self.view.bounds.size.width,
(float)self.view.bounds.size.height)];
webView.tag=55;
NSString* combinedString = [self.urlToLoad stringByAppendingString:@"/redzone"];
NSLog(@"requestURL : %@",combinedString);
NSURL *url = [[NSURL alloc] initWithString:combinedString];
NSMutableURLRequest *request;
request = [[NSMutableURLRequest alloc] initWithURL: url];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
ontracHTTPModel *model = [ontracHTTPModel sharedManager];
if (![model.cookieAuth isEqualToString:@""])
NSDictionary *cookieProperties = [NSDictionary dictionaryWithObjectsAndKeys:
@"MYCOOKIE", NSHTTPCookieName,
@"mydomain.com", NSHTTPCookieDomain,
model.cookieValue, NSHTTPCookieValue,
@"/", NSHTTPCookiePath,
nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
NSArray* cookieArray = [NSArray arrayWithObjects: cookie, nil];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
[request setAllHTTPHeaderFields:headers];
NSError *error;
NSString *webData= [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
webView.scalesPageToFit = YES;
webView.delegate = self;
[webView loadhtmlString:webData baseURL:nil];
[self.view addSubview:webView];
【讨论】:
以上是关于IOS UIWebView添加Cookie值请求的主要内容,如果未能解决你的问题,请参考以下文章