How to set the HTTP body for a request using AFNetworking?


In the early versions of AFNetworking if I had to make my own custom client then I would simply inherit from AFHTTPClient and create my methods. In AFNetworking 2.0 I believe I need to inherit from AFHTTPSessionManager.

@interface MyCustomClient : AFHTTPSessionManager { }

In my situation I need to send in request as soap. This means that HTTP Body will be soap and HTTP HEADERS will be text/xml.

Let's say I have a variable which contains the entire soap body I need to send to the server.

NSString *soapBody = @"Soap body";

Using my custom class defined above which inherits from AFHTTPSessionManager how will I set the soap body to the Request HTTPBody.

If there is anyway to access NSURLRequest from inside the AFHTTPSessionManager then I can simply do setHTTPBody but it seems there is not?

I hope I am making sense now!


You should create a subclass of AFHTTPRequestSerializer, then implement the protocol AFURLRequestSerialization, this class is going to care about adding the body and headers to the request

- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request withParameters:(id)parameters error:(NSError * __autoreleasing *)error { NSParameterAssert(request); if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { return [super requestBySerializingRequest:request withParameters:parameters error:error]; } NSMutableURLRequest *mutableRequest = [request mutableCopy]; [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { if (![request valueForHTTPHeaderField:field]) { [mutableRequest setValue:value forHTTPHeaderField:field]; } }]; [mutableRequest setValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [mutableRequest setHTTPBody:@"This is the soap Body!!"]; return mutableRequest; }

You can read the implementation or other AFHTTPRequestSerializer subclasses <a href="https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFURLRequestSerialization.m#L1094" rel="nofollow">https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFURLRequestSerialization.m#L1094</a>


Init a NSMutableURLRequest *request; and set httpBody to request by: [request setHTTPBody:[soapMessage dataUsingEncoding:NSUTF8StringEncoding]];

You can try this code.

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestURL]]; request.HTTPMethod = @"POST"; [request setValue:@"application/soap+xml;charset = utf-8" forHTTPHeaderField:@"Content-Type"]; request.HTTPBody = [soapMessage dataUsingEncoding:NSUTF8StringEncoding]; NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil]; NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error) { // parse response here } else { // error } }]; [sessionTask resume];

hope it help You.


  • How to save the data in JSON dictionary and to send the web service post call?
  • Authentication with Back-end Spring Security Java EE Server and Front-end iOS Objective-C client
  • Calling web services with the help of AFNetworking in Objective C
  • Avoid UIWebView load iTunes App
  • Error getting audio input device sample rate: '!obj'
  • Intermittent JSON parser failure for unescaped control character
  • UILongPressGestureRecognizer not working
  • Is it OK to write code after [super dealloc]?
  • Add filename and length parameter to WCF stream when Transfermode = Stream
  • wsContext.getMessageContext().get(MessageContext.SERVLET_REQUEST) returns null on Jetty?
  • Testing custom SOAP Headers in ASMX
  • in batch how do i use taskkill properly
  • Using same constraints in multiple classes
  • LiveData is abstract android
  • Retrieving specified columns from a list of csv files to create a data data frame in R
  • How to make Twilio api Post request with the help of AFNetworking?
  • uml Composition relationships to RDF and OWL
  • Clear activity stack before launching another activity
  • Azure table store snapshot/backup capability
  • Filter strings with regex before casting to numeric
  • Undefined references when compiling gSOAP client
  • C# program and C++ DLL compiled for 32-bit system crash on 64-bit system
  • xtable package: Skipping some rows in the output
  • Caching attributes in superclass
  • Why Encoding.ASCII != ASCIIEncoding.Default in C#?
  • one Local Olampyad Questions on Informatic in 2011
  • Refering to the class itself from within a class mehod in Objective C
  • formatting the colorbar ticklabels with SymLogNorm normalization in matplotlib
  • Change JButton Shape while respecting Look And Feel
  • Get object from AWS S3 as a stream
  • Apache 2.4 - remove | delete | uninstall
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • KeystoneJS: Relationships in Admin UI not updating
  • Benchmarking RAM performance - UWP and C#
  • Java static initializers and reflection
  • unknown Exception android
  • Observable and ngFor in Angular 2
  • Unable to use reactive element in my shiny app
  • Net Present Value in Excel for Grouped Recurring CF