objective-c – 为什么在设置NSHTTPCookie后,它是否未附加到NSURLRequest?

我正在设置(或尝试设置)NSHTTPCookie,如下所示:

+ (void)setCookie {

  NSString* cookieName = @"MyCookieName";
  NSString* cookieValue = @"MyCookieValue";
  NSString* cookieOriginURL = @"www.mycompany.com";
  NSString* cookiePath = @"/";

  NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
  [cookieProperties setObject:cookieName      forKey:NSHTTPCookieName];
  [cookieProperties setObject:cookieValue     forKey:NSHTTPCookieValue];
  [cookieProperties setObject:cookieOriginURL forKey:NSHTTPCookieOriginURL];
  [cookieProperties setObject:cookiePath      forKey:NSHTTPCookiePath];

  [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:3600] forKey:NSHTTPCookieExpires];

  NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties];
  [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];

}

调用此方法后,我创建一个NSURLRequest:

NSString *urlAddress = @"http//:www.mycompany.com/mobile/home";

//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];

//URL Request Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

NSLog(@"Here's the request: %@", [requestObj description]);

//Load the request in the UIWebView.
[self.webView loadRequest:requestObj];

但输出是:

Here's the request: <NSURLRequest: 0xa33a4d0> { URL: http:www.mycompany.com/mobile/home

我希望看到cookie信息附加到请求,但事实并非如此.

我对cookie知之甚少,所以我不知道我的代码是否遗漏了什么,或者我只是想念解输出的含义.

谢谢你的帮助.

最佳答案 我怀疑NSURLRequest的描述是否会提供cookie信息.

域是匹配(cookie和URL),因此cookie必须附加到请求.在触发请求之前执行以下代码,以查看与您的请求一起发送的cookie.

NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for(NSHTTPCookie *cookie in [cookieJar cookiesForURL:url]) {
        NSLog(@"Cookies attached: %@", cookie.description);
}
点赞