如何从Objective-c中返回302而不是200的Http Post捕获cookie
目前,如果我执行http GET或POST并返回200瓦/类型的应用程序/ json或xml我可以捕获使用此方法发回的cookie
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];
}
但是当请求返回302(重定向)时,我该如何捕获cookie在init请求期间发送到客户端?目前,只有在重定向发生后,我才会收到GET请求200之后发回的cookie
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
更新
我发现最终的解决方案如下。我需要if语句来验证resp是否有效,因为在我的实例中这个方法总共被调用了3次。一次用于初始化请求,然后再次用于302(我关心的那个),最后用于重定向网址的最后一次GET请求
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 = [NSHTTPCookie
cookiesWithResponseHeaderFields:[response allHeaderFields]
forURL:[NSURL URLWithString:@""]];
if ([zzzz count] > 0) {
//do something with cookies
}
}
return request;
}
NSURLRequest上有委托方法您可以使用:
There's delegate method on NSURLRequest that you can use for that:
connection:willSendRequest:redirectResponse:
当您收到重定向回复时,您可以从中提取Cookie。
As you'll get the redirect response, you can extract the cookies from it.