How to capture cookies from an Http Post that returns 302 instead of 200 in objective-c
Currently if I do an http GET or POST and it returns 200 w/ a type of application/json or xml I can capture the cookies sent back using this method
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSArray* returnedCookies = [NSHTTPCookie
cookiesWithResponseHeaderFields:[response allHeaderFields]
forURL:[NSURL URLWithString:@""]];
[responseData setLength:0];
}
But when the request returns a 302 (redirect) how can I capture the cookies sent down to the client during the init request? Currently I only get the cookies sent back after the 200 from the GET request following this redirect occurs
Update
What I found to be the final solution is below. I needed the if statements to verify the resp was valid as this method is called a total of 3 times in my instance. Once for the init request, then again for the 302 (the one I care about) and finally for the last GET request for the redirected url
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSHTTPURLResponse *)response {
if (response != nil) {
NSArray* cookies = [NSHTTPCooki开发者_开发问答e
cookiesWithResponseHeaderFields:[response allHeaderFields]
forURL:[NSURL URLWithString:@""]];
if ([zzzz count] > 0) {
//do something with cookies
}
}
return request;
}
There's delegate method on NSURLRequest that you can use for that:
connection:willSendRequest:redirectResponse:
As you'll get the redirect response, you can extract the cookies from it.
精彩评论