【问题标题】:iPhone Make POST request, handle cookieiPhone 发出 POST 请求,处理 cookie
【发布时间】:2009-11-02 12:09:01
【问题描述】:

我希望有人可以对以下内容有所了解,我认为我正朝着正确的方向前进。我想使用用户/密码组合登录到我的服务器,然后我需要能够判断我是否正确登录(应该删除 cookie),如果是这种情况,我将发出另一个请求。

感谢任何帮助,这是我正在使用的代码:

[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];

NSString *post =[NSString stringWithFormat:@"name=%@&pass=%@",@"foo", @"bar"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.mywebserver.com/login.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(data);

// HOW to Check if there was a Cookie dropped??


// Make another request..

【问题讨论】:

    标签: iphone forms post


    【解决方案1】:

    这应该可行:

    NSDictionary *headerFields = [(NSHTTPURLResponse*)response allHeaderFields]; 
    NSURL *url = [NSURL URLWithString:@"http://www.mywebserver.com/login.php"];   
    NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:headerFields forURL:url];
    

    那么你就可以知道cookies数组中是否包含你想要的cookie。

    您也可以在收到响应后调用:

    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
    

    【讨论】:

      【解决方案2】:

      这是使用您当前代码的可能解决方案:

      1 - 一开始做的很好:一般设置cookie策略。

      NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHttpCookieStorage];
      [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
      

      2 - 之后,在您的请求中,您需要指定要使用 cookie(以便注入会话信息):

      [request setHTTPShouldHandleCookies:YES];
      

      您需要为身份验证和后续请求设置此字段。

      【讨论】:

      • 只是一个快速的更正,它应该是:NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHttpCookieStorage];谢谢你的信息!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 2015-08-30
      • 2019-03-19
      • 1970-01-01
      相关资源
      最近更新 更多