我在AFNetworking
切换后尝试使用ASIHTTPRequest
。
我会使用AFHTTPClient
向我的api后端服务器发出请求。目前我发出了一个请求(没有AFNetworking
)来获取csrf令牌(我使用Django)之前每个 POST请求AFNetworking
(我从www.example.org/api/csrf
得到它)。我这样做是因为我需要为每个POST请求提供csrf令牌。
有没有办法在AFHTTPClient
?
编辑:
在每个POST请求之前获取csrf令牌的代码是:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:kTokenURL]];
NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [jsonString objectFromJSONString];
NSString *csrf_token = [jsonDict objectForKey:@"csrf_token"];
[jsonString release];
NSLog(@"token: %@", csrf_token);
答案 0 :(得分:3)
是的,创建一个AFHTTPClient子类(在AFNetworking附带的示例项目中有一个例子)
在@interface文件中:
#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"
@interface HttpClientSubclass : AFHTTPClient
+ (HttpClientSubclass *)sharedClient;
@end
在您的实施文件中:
#import "HttpClientSubclass.h"
@implementation HttpClientSubclass
+ (HttpClientSubclass *)sharedClient {
static HttpClientSubclass *_sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"BASE-URL-GOES_HERE"]];
});
return _sharedClient;
}
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
path:(NSString *)path
parameters:(NSDictionary *)parameters {
if ([method isEqualToString:@"POST"])
//GET YOUR CSRF TOKEN HERE, AND PASS ONTO THE SUPER CLASS IN THE PARAMETERS
return [super requestWithMethod:method path:path parameters:parameters];
}
@end