我使用下面的代码来创建cookie,但是失败了。(IOS SDK5)
// add cookie
NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
req.URL, NSHTTPCookieOriginURL,
@"MLSTORAGE", NSHTTPCookieName,
@"1234567890", NSHTTPCookieValue,
nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];
NSLog(@"\nurl: %@\ncookie: %@", req.URL, cookie);
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
//日志为:
2012-07-26 18:30:49.914 Motilink[15289:707] -[FMWebDAVRequest sendRequest:][Line 154]
url: http://210.116.114.195:8080/MLServer/storage/
cookie: (null)有人知道如何创建cookie吗?
发布于 2013-04-12 16:02:01
似乎在将NSHTTPCookieOriginURL与请求的URL一起使用时出现了问题。
试着使用下面的代码,它对我很有效:
// add cookie
NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys:
req.URL.host, NSHTTPCookieDomain,
req.URL.path, NSHTTPCookiePath,
@"MLSTORAGE", NSHTTPCookieName,
@"1234567890", NSHTTPCookieValue,
nil];
NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:properties];
NSLog(@"\nurl: %@\ncookie: %@", req.URL, cookie);
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
//然而,我不知道为什么NSHTTPCookieOriginURL不能在这里工作。
希望这能帮上忙
发布于 2015-02-12 11:50:50
要成功创建cookie,必须提供(至少) NSHTTPCookiePath、NSHTTPCookieName和NSHTTPCookieValue密钥以及NSHTTPCookieOriginURL密钥或NSHTTPCookieDomain密钥的值。
发布于 2018-02-08 23:34:12
我也遇到过同样的问题。当我查阅文档,发现只有'name','value‘和'originURL’或'domain‘属性是必需的时,我尝试了,但失败了。在我添加了'path‘之后,它就起作用了。因为我没有准确地理解,如果你只提供了'domain‘而不是'originURL','path’也是必需的。
<tr>
<th>Property key constant</th>
<th>Type of value</th>
<th>Required</th>
<th>Description</th>
</tr>
<tr>
<td>NSHTTPCookieName</td>
<td>NSString</td>
<td>YES</td>
<td>Name of the cookie</td>
</tr>
<tr>
<td>NSHTTPCookieValue</td>
<td>NSString</td>
<td>YES</td>
<td>Value of the cookie</td>
</tr>
<tr>
<td>NSHTTPCookieDomain</td>
<td>NSString</td>
<td>Special, a value for either NSHTTPCookieOriginURL or
NSHTTPCookieDomain must be specified.</td>
<td>Domain for the cookie. Inferred from the value for
NSHTTPCookieOriginURL if not provided.</td>
</tr>
<tr>
<td>NSHTTPCookieOriginURL</td>
<td>NSURL or NSString</td>
<td>Special, a value for either NSHTTPCookieOriginURL or
NSHTTPCookieDomain must be specified.</td>
<td>URL that set this cookie. Used as default for other fields
as noted.</td>
</tr>
<tr>
<td>NSHTTPCookiePath</td>
<td>NSString</td>
<td>NO</td>
<td>Path for the cookie. Inferred from the value for
NSHTTPCookieOriginURL if not provided. Default is "/".</td>
</tr>最终代码如下:
NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
[cookieProperties setObject:@"SESSION" forKey:NSHTTPCookieName];
[cookieProperties setObject:@"value" forKey:NSHTTPCookieValue];
[cookieProperties setObject:@".domain.com" forKey:NSHTTPCookieDomain];
[cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
NSHTTPCookie *co = [NSHTTPCookie cookieWithProperties:cookieProperties];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:co];https://stackoverflow.com/questions/11667468
复制相似问题