【问题标题】:Can't set cookie in NSURLRequest无法在 NSURLRequest 中设置 cookie
【发布时间】:2012-08-05 19:29:43
【问题描述】:

在我的程序中,我调用了两个函数,第一个是登录,第二个是解析数据的函数。

为了存储会话,我使用登录功能保存我的 cookie:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
    if(connection == conn_login){
        NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
        NSDictionary *fields = [HTTPResponse allHeaderFields];
        cookie = [fields valueForKey:@"Set-Cookie"];
    }
}

一切都很好,当我打印 cookie 时:

userid=1; expires=Mon, 05-Aug-2013 19:22:18 GMT; path=/; domain=www.mydomain.com

“userid=1”是我感兴趣的。

所以在下面我解析数据的 NSURLRequest 中,我确实喜欢这样设置保存的 cookie:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL
URLWithString:@"http://www.mydomain.com/?getList"]];
[request setValue:cookie forHTTPHeaderField:@"Set-Cookie"];

但它不起作用。我以前的 cookie 没有设置,即使打印第二个请求的完整标头,也没有“用户 ID”或任何东西。

我做错了什么?谢谢大家。

【问题讨论】:

    标签: objective-c xcode cookies nsurlconnection nsurlrequest


    【解决方案1】:

    我认为您必须使用这行代码...如果您有疑问,请告诉我

    NSArray *cookies1 = [[ NSHTTPCookieStorage sharedHTTPCookieStorage] cookies ];
    
    NSDictionary *cookieHeaders;
    
    cookieHeaders = [ NSHTTPCookie requestHeaderFieldsWithCookies: cookies1];
    
    [request setValue: [cookieHeaders objectForKey: @"Cookie" ]forHTTPHeaderField:@"Cookie" ];
    

    【讨论】:

      猜你喜欢
      • 2020-06-29
      • 2011-12-27
      • 2015-05-20
      • 2013-05-02
      • 2013-06-12
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 2021-09-12
      相关资源
      最近更新 更多