如何在AFNetworking 2.0+中使用AFHTTPRequestOperationManager使用Cookie? [英] How can I use cookies using AFHTTPRequestOperationManager in AFNetworking 2.0+?

查看:101
本文介绍了如何在AFNetworking 2.0+中使用AFHTTPRequestOperationManager使用Cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,AFNetworking 2.0+中的 AFHTTPSessionManager 支持cookie。

As it is known, AFHTTPSessionManager in AFNetworking 2.0+ supports cookies.

但是 AFHTTPRequestOperationManager是否可能在AFNetworking 2.0+中支持cookie?

But is it possible for AFHTTPRequestOperationManager in AFNetworking 2.0+ to support cookies?

推荐答案

是。 AFNetworking使用基础URL加载系统,该系统可立即处理Cookie。

Yes. AFNetworking uses the foundation URL Loading system, which handles cookies out of the box.

您可以配置NSMutableURLRequest的 setHTTPShouldHandleCookies 和使用 NSHTTPCookieStorage 来存储它们。

You can configure NSMutableURLRequest's setHTTPShouldHandleCookies and use NSHTTPCookieStorage to store them.

在Objective-C中:

In Objective-C:

NSArray *cookieStorage = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
NSDictionary *cookieHeaders = [NSHTTPCookie requestHeaderFieldsWithCookies:cookieStorage];
NSMutableURLRequest *request = [myRequestSerializer requestWith…];
for (NSString *key in cookieHeaders) {
    [request addValue:cookieHeaders[key] forHTTPHeaderField:key];
}

在Swift中:

var request = NSMutableURLRequest() // you can use an AFNetworking Request Serializer to create this

if let cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(url) {
    for (headerField, cookie) in NSHTTPCookie.requestHeaderFieldsWithCookies(cookieStorage) {
        request.addValue(cookie, forHTTPHeaderField: headerField)
    }
}

这篇关于如何在AFNetworking 2.0+中使用AFHTTPRequestOperationManager使用Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆