如何从Objective-c中返回302而不是200的Http Post捕获cookie [英] How to capture cookies from an Http Post that returns 302 instead of 200 in objective-c

查看:126
本文介绍了如何从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.

这篇关于如何从Objective-c中返回302而不是200的Http Post捕获cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆