ios - 如何使用 NSURLRequest 设置 Cookie?

标签 ios objective-c

我正在尝试在我的 iPhone 应用程序中创建登录。

NSURL *urlNew = [NSURL URLWithString:urlstring];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:urlNew];
NSString *msgLength = [NSString stringWithFormat:@"%d", [parameterString length]];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setValue:length forHTTPHeaderField:@"Content-Length"];
[theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[theRequest setHTTPBody: httpbody];
         
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
         
[connection start];

这就是我将数据发布到服务器的方式,它有效 - 我得到了响应。问题是,响应是登录端的代码,而不是“已保存”区域的代码。我想我必须创建 cookie,以便网站知道我已登录。

我在网上搜索过,但没有找到任何有用的东西。那么我如何在登录时创建 cookie?当我转到“已保存”区域中的另一个链接时,是否每次都必须发布此 cookie?

最佳答案

试试这个

[theRequest setValue:@"myCookie" forHTTPHeaderField:@"Cookie"];

编辑:

OP 想知道如何创建 cookie。所以这里有一些代码

NSDictionary *cookieProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                        @"domain.com", NSHTTPCookieDomain,
                        @"\\", NSHTTPCookiePath,  
                        @"myCookie", NSHTTPCookieName,
                        @"1234", NSHTTPCookieValue,
                        nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
NSArray* cookieArray = [NSArray arrayWithObject:cookie];
NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieArray];
[request setAllHTTPHeaderFields:headers];

关于ios - 如何使用 NSURLRequest 设置 Cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9250076/

相关文章:

javascript - 为什么 Stripe Element 不能在 iphone 上运行,但在 Android 和桌面上运行良好?

ios - TextField 的代表

objective-c - CSV 文件查找 - Objective C

ios - 来自 firebase 控制台 iOS 12.2 的推送通知不起作用

C++ 生成器 10 CoreFondation.h(12) : 'Stdarg.h' file not found

iphone - Facebook 不允许使用 ios 应用程序的帐户

ios - UICollectionViewCell 中的 MKMapView,didSelectItemAtIndexPath 未调用

ios - 如何更改搜索栏后面的背景颜色

objective-c - 防止 UIScrollView 在发生触摸时停止滚动

iphone - 我如何在 UITableView 上添加 UIActivityIndi​​cator