如何使用NSURLRequest设置Cookie?

Sch*_*rsi 13 iphone xcode 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];
Run Code Online (Sandbox Code Playgroud)

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

我搜索了互联网,但没有找到任何有用的东西.那么当我登录时,如何创建cookie?当我要去"已保存"区域中的另一个链接时,我是否每次都要发布此cookie?

希望你解开我的问题.

格尔茨

mbh*_*mbh 30

试试这个

[theRequest setValue:@"myCookie" forHTTPHeaderField:@"Cookie"];
Run Code Online (Sandbox Code Playgroud)

编辑:

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];
Run Code Online (Sandbox Code Playgroud)