简体   繁体   中英

AFNetworking set default value for POST request

I'm trying to using AFNetworking after the switch from ASIHTTPRequest .

I would use AFHTTPClient for making request to my api backend server. Currently I make a request (without AFNetworking ) for getting the csrf token (I use Django) before every POST request with AFNetworking (I get it from www.example.org/api/csrf ). I do this because I need the csrf token for every POST request.

Is there a way to make this task automatically in the AFHTTPClient ?

EDIT:

The code for getting the csrf token before every POST request is:

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

Yep, create a AFHTTPClient Subclass (there is an example of this in the example project that comes with AFNetworking)

In your @interface file:

#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"

@interface HttpClientSubclass : AFHTTPClient
    + (HttpClientSubclass *)sharedClient;
@end

In your implementation file:

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM