我正在尝试在我的 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/