iPhone发出POST请求,处理cookie

标签 iphone forms post

我希望有人能够阐明以下内容,我认为我正在朝着正确的方向前进。我想使用用户/密码组合登录我的服务器,然后我需要能够判断我是否正确登录(应该删除 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..

最佳答案

这应该有效:

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];

关于iPhone发出POST请求,处理cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1660927/

相关文章:

iphone - 有没有适用于 Android 的 iUI

iphone - iPhone 上的 Z 星 : how can i scan qrcode without include zxing widget in my application?

java - 回复:POST:java.io.IOException:不支持的媒体类型

html - POST 未选中的 HTML 复选框

http - 使用 POST 参数压缩 HTTP 文本

iphone - 在 Objective-C 中释放对象的正确方法是什么

iphone - 我为使用 makefile 构建的 iO 寻找库项目

jquery - 在 <input> html 5 表单中使用多个模式进行验证

javascript - 调用文件删除页面后返回页面状态

javascript - 提交按钮清除表单而不是打开 div