从NSHTTPURLResponse

时间:2017-02-19 03:36:02

标签: objective-c cocoa foundation

我试图访问http响应中发送的Set-Cookie标头:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
    NSDictionary *headers = [httpResponse allHeaderFields];
    NSLog([headers description]);
}

HTTP服务器发送两个Set-Cookie标题,如下所示:

Set-Cookie: foo=1; httponly; Path=/
Set-Cookie: bar=2; httponly; Path=/

但是,[HTTPResponse allHeaderFields]接口正在将多个Set-Cookie标头组合成一个以逗号分隔的字符串:

"Set-Cookie" = "foo=1; httponly; Path=/, bar=2; httponly; Path=/"

This cocoa-dev mailing list message证实了我的观察。

是否有一个接口可以单独获取每个Set-Cookie标头或访问原始标头?

1 个答案:

答案 0 :(得分:1)

iOS和macOS定义了一个NSHTTPCookie类,它可以解析并为您提供您正在寻找的信息:

NSArray<NSHTTPCookie *> *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields: [httpResponse allHeaderFields] forURL: [httpResponse url]];

有关详细信息,请参阅NSHTTPCookie的{​​{3}}。

相关问题