Skip to content

Instantly share code, notes, and snippets.

@AquaGeek
Created May 1, 2012 17:08
Show Gist options
  • Save AquaGeek/2569692 to your computer and use it in GitHub Desktop.
Save AquaGeek/2569692 to your computer and use it in GitHub Desktop.
AFNetworking with XML request body
#import <Foundation/Foundation.h>
#import "AFHTTPClient.h"
@interface APIClient : AFHTTPClient
+ (APIClient *)sharedClient;
@end
#import "APIClient.h"
#import "AFXMLRequestOperation.h"
// Define our additional parameter encoding
enum {
XMLParameterEncoding = 10
};
@interface APIClient()
- (void)addHTTPBodyToRequest:(NSMutableURLRequest *)request
withParameters:(NSDictionary *)parameters
charset:(NSString *)charset;
@end
#pragma mark -
@implementation APIClient
// We override this method so that we can properly set the request body
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters
{
NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters];
NSSet *methodsWithNoBody = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil];
if (parameters != nil && ![methodsWithNoBody containsObject:method])
{
NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
[self addHTTPBodyToRequest:request withParameters:parameters charset:charset];
}
return request;
}
- (void)addHTTPBodyToRequest:(NSMutableURLRequest *)request withParameters:(NSDictionary *)parameters charset:(NSString *)charset
{
switch (self.parameterEncoding)
{
case XMLParameterEncoding: // If it's our custom encoding...
{
[request setValue:[NSString stringWithFormat:@"application/xml; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
// Create the request body
NSMutableString *body = [NSMutableString string];
// ** Append your XML request to the body string here **
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
break;
}
default:
{
break;
}
}
// ** Set any additional headers, etc here **
}
+ (APIClient *)sharedClient
{
static APIClient *sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^(void)
{
NSURL *baseURL = [NSURL URLWithString:@"https://yourserver.com/path/to/your/api/"];
sharedClient = [[self alloc] initWithBaseURL:baseURL];
[sharedClient registerHTTPOperationClass:[AFXMLRequestOperation class]];
// ** Set any default headers **
[sharedClient setDefaultHeader:@"my-header" value:@"blah"];
// Use our custom parameter encoding
sharedClient.parameterEncoding = XMLParameterEncoding;
});
return sharedClient;
}
@end
@cokecoffe
Copy link

could you show how to use it? thx.

@haitham-reda
Copy link

would appreciate any tutorial/working sample code.

thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment