Sca*_*car 8 cookies objective-c nsurlrequest nshttpurlresponse
我有一个非常奇怪的问题,我正在请求一个URL,我想从中获取cookie,我用这种方式来获取cookie:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
NSDictionary *fields = [HTTPResponse allHeaderFields];
NSString *cookie = [fields valueForKey:"Set-Cookie"];
}
Run Code Online (Sandbox Code Playgroud)
但是饼干不完整,有一些字段缺失,我在PostMan上检查过,所有的饼干都在那里.
我在启动时也使用了这种方法NSURLRequest.
[request setHTTPShouldHandleCookies:YES];
Run Code Online (Sandbox Code Playgroud)
问题出在哪儿?
注意:这个问题是在iOS上,我是一个Android版本,它工作正常,所有的cookie都在那里.
Ash*_*ani 14
您是否尝试过以下代码示例,它应该可以工作:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSArray *cookies =[[NSArray alloc]init];
cookies = [NSHTTPCookie
cookiesWithResponseHeaderFields:[response allHeaderFields]
forURL:[NSURL URLWithString:@""]]; // send to URL, return NSArray
}
Run Code Online (Sandbox Code Playgroud)
试试这段代码:
for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
NSLog(@"name: '%@'\n", [cookie name]);
NSLog(@"value: '%@'\n", [cookie value]);
NSLog(@"domain: '%@'\n", [cookie domain]);
NSLog(@"path: '%@'\n", [cookie path]);
}
Run Code Online (Sandbox Code Playgroud)
@ biloshkurskyi.ss答案就是现场.
我花了半天的时间试图找出为什么我的一些cookie没有出现在我的response.allHeaderFields iOS上,但它出现在Android上(使用相同的服务).
原因是因为某些cookie被提前提取并存储在共享cookie存储中.它们不会出现在allHeaderFields中.
如果有人需要,这是答案的快速3版本:
let request = URLRequest(url: myWebServiceUrl)
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let error = error {
print("ERROR: \(error)")
} else {
print("RESPONSE: \(response)")
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("DATA: " + dataString)
}
for cookie in HTTPCookieStorage.shared.cookies! {
print("EXTRACTED COOKIE: \(cookie)") //find your cookie here instead of httpUrlResponse.allHeaderFields
}
}
})
task.resume()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15506 次 |
| 最近记录: |