AFNetworking设置POST请求的默认值

时间:2012-02-13 21:06:09

标签: iphone ios afnetworking

我在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);

1 个答案:

答案 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