2011-03-02 36 views
1

我正在做一個簡單的登錄,並注意到在重定向期間,我只有3個必需的cookie中的2個才能正確登錄。我抓住了另一個cookie並將它們放在一起,但由於某種原因,我無法動態修改頭文件?如何在objective-c重定向期間修改請求的cookie?

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSHTTPURLResponse *)response { 
    NSURL* redirected_url = [request URL]; 
    NSString* querystr = [redirected_url absoluteString]; 

    if (response != nil) { 
     NSArray* zzzz = [NSHTTPCookie 
         cookiesWithResponseHeaderFields:[response allHeaderFields] 
         forURL:[NSURL URLWithString:@""]]; 

     if ([zzzz count] > 0) { 
      if ([querystr isEqualToString:@"https://www.localhost.com/specificurl.aspx"]) { 
       NSMutableArray* actualCookies = [[NSMutableArray alloc] init]; 

       NSHTTPCookie* obj = [self.tmpCookies objectAtIndex:0]; 
       [actualCookies addObject:obj]; 
       [actualCookies addObject:zzzz]; 

       NSArray* authToken = [[NSArray alloc] initWithArray:actualCookies]; 

       //BLOWS UP HERE ?? NSDictionary* headers = [NSHTTPCookie requestHeaderFieldsWithCookies:authToken]; 
       //[request setAllHTTPHeaderFields:authToken]; 

       [viewController setAuthCookieAfterValidLogin:zzzz]; 
      } 
     } 
    } 

    return request; 
} 

的總體思路是:設置這個頭有我相結合的cookie值

回答

3

我發現,雖然我不能修改現有的要求,這並沒有創建一個新的阻止我請求,並簡單地返回那一個:)

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSHTTPURLResponse *)response { 
    NSURL* redirected_url = [request URL]; 
    NSString* querystr = [redirected_url absoluteString]; 

    if (response != nil) { 
     NSArray* zzzz = [NSHTTPCookie 
         cookiesWithResponseHeaderFields:[response allHeaderFields] 
         forURL:[NSURL URLWithString:@""]]; 

     if ([zzzz count] > 0) { 
      if ([querystr isEqualToString:@"https://www.localhost.com/specificurl.aspx"]) { 
       NSMutableArray* actualCookies = [[NSMutableArray alloc] init]; 
       NSUInteger i, count = [zzzz count]; 
       for (i = 0; i < count; i++) { 
        NSHTTPCookie* xxx = [zzzz objectAtIndex:i]; 
        [actualCookies addObject:xxx]; 
       } 

       NSHTTPCookie* obj = [self.tmpCookies objectAtIndex:0]; 
       [actualCookies addObject:obj]; 

       NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:actualCookies]; 

       NSURL *url = [NSURL URLWithString:@"https://www.localhost.com/specificurl.aspx"]; 
       NSMutableURLRequest* xrequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 

       [xrequest setHTTPMethod:@"GET"]; 
       [xrequest setAllHTTPHeaderFields:headers]; 
       [xrequest setValue:@"https://www.localhost.com/Default.aspx?Site_ID=500000" forHTTPHeaderField: @"Referer"]; 

       [viewController setAuthCookieAfterValidLogin:zzzz]; 

       return xrequest; 
      } 
     } 
    } 

    return request; 
}