How to set HTTP request body using AFNetwork's AFHTTPRequestOperationManager? - ios

I am using AFHTTPRequestOperationManager (2.0 AFNetworking library) for a REST POST request. But the manager only have the call to set the parameters.
-((AFHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
I need to set HTTP request body with a string as well. How can I do it using the AFHTTPRequestOperationManager? Thanks.

I had the same problem and solved it by adding code as shown below:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue:#"Basic: someValue" forHTTPHeaderField:#"Authorization"];
[request setValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON responseObject: %# ",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
}];
[op start];

for AFHTTPRequestOperationManager
[requestOperationManager.requestSerializer setValue:#"your Content Type" forHTTPHeaderField:#"Content-Type"];
[requestOperationManager.requestSerializer setValue:#"no-cache" forHTTPHeaderField:#"Cache-Control"];
// Fill parameters
NSDictionary *parameters = #{#"name" : #"John",
#"lastName" : #"McClane"};
// Customizing serialization. Be careful, not work without parametersDictionary
[requestOperationManager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
NSString *argString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return argString;
}];
[requestOperationManager POST:urlString parameters:parameters timeoutInterval:kRequestTimeoutInterval success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success)
success(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure)
failure(error);
}];

Check what that convenience method (POST:parameters:success:failure) is doing under the hood and do it yourself to get access to actual NSMutableRequest object.
I'm using AFHTTPSessionManager instead of AFHTTPRequestOperation but I imagine the mechanism is similar.
This is my solution:
Setup Session Manager (headers etc)
Manually create NSMutable request and add my HTTPBody, basically copying-pasting code inside that convenience method. Looks like this:
NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:#"POST" URLString:[[NSURL URLWithString:<url string>] absoluteString] parameters:parameters];
[request setHTTPBody:[self.POSTHttpBody dataUsingEncoding:NSUTF8StringEncoding]];
__block NSURLSessionDataTask *task = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
if (error) {
// error handling
} else {
// success
}
}];
[task resume];

If you dig a little in sources of AFNetworking you will find that in case of POST method parameters are set into body of your HTTP request.
Each key,value dictionary pair is added to the body in form key1=value1&key2=value2. Pairs are separated by & sign.
Search for application/x-www-form-urlencoded in AFURLRequestSerialization.m.
In case of a string which is only a string, not key value pair then you might try to use AFQueryStringSerializationBlock http://cocoadocs.org/docsets/AFNetworking/2.0.3/Classes/AFHTTPRequestSerializer.html#//api/name/setQueryStringSerializationWithBlock: but this is only my guess.

You could create your own custom subclass of AFHTTPRequestSerializer, and set this as the requestSerializer for your AFHTTPRequestOperationManager.
In this custom requestSerializer, you could override
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error;
Inside your implementation of this method, you'll have access to the NSURLRequest, so you could do something like this
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSURLRequest *serializedRequest = [super requestBySerializingRequest:request withParameters:parameters
error:error];
NSMutableURLRequest *mutableRequest = [serializedRequest mutableCopy];
// Set the appropriate content type
[mutableRequest setValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
// 'someString' could eg be passed through and parsed out of the 'parameters' value
NSData *httpBodyData = [someString dataUsingEncoding:NSUTF8StringEncoding];
[mutableRequest setHTTPBody:httpBodyData];
return mutableRequest;
}
You could take a look inside the implementation of AFJSONRequestSerializer for an example of setting custom HTTP body content.

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:url parameters:jsonObject success:^(AFHTTPRequestOperation *operation, id responseObject) {
//success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//fail
}];
This is the best and most concise way that I have found.

May be we can use the NSMutableURLRequest, here is the code :
NSURL *url = [NSURL URLWithString:yourURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
NSString *contentJSONString = [[NSString alloc] initWithData:JSONData encoding:NSUTF8StringEncoding];
[request setHTTPBody:[contentJSONString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];

Related

AFNetworking 3 - objective c - send data without key [duplicate]

I am trying to make an HTTP PUT request using AFNetworking to create an attachment in a CouchDB server. The server expects a base64 encoded string in the HTTP body. How can I make this request without sending the HTTP body as a key/value pair using AFNetworking?
I began by looking at this method:
- (void)putPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
But here the parameters are to be of type: NSDictionary. I just want to send a base64 encoded string in the HTTP body but not associated with a key. Can someone point me to the appropriate method to use? Thanks!
Hejazi's answer is simple and should work great.
If, for some reason, you need to be very specific for one request - for example, if you need to override headers, etc. - you can also consider building your own NSURLRequest.
Here's some (untested) sample code:
// Make a request...
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL];
// Generate an NSData from your NSString (see below for link to more info)
NSData *postBody = [NSData base64DataFromString:yourBase64EncodedString];
// Add Content-Length header if your server needs it
unsigned long long postLength = postBody.length;
NSString *contentLength = [NSString stringWithFormat:#"%llu", postLength];
[request addValue:contentLength forHTTPHeaderField:#"Content-Length"];
// This should all look familiar...
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postBody];
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:success failure:failure];
[client enqueueHTTPRequestOperation:operation];
The NSData category method base64DataFromString is available here.
You can use multipartFormRequestWithMethod method as following:
NSURLRequest *request = [self multipartFormRequestWithMethod:#"PUT" path:path parameters:parameters constructingBodyWithBlock:^(id <AFMultipartFormData> formData) {
[formData appendString:<yourBase64EncodedString>]
}];
AFHTTPRequestOperation *operation = [client HTTPRequestOperationWithRequest:request success:success failure:failure];
[client enqueueHTTPRequestOperation:operation];
Here you have an example sending a raw json:
NSDictionary *dict = ...
NSError *error;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:&error];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:YOUR_URL parameters:nil error:nil];
req.timeoutInterval = 30;
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:IF_NEEDED forHTTPHeaderField:#"Authorization"];
[req setHTTPBody:dataFromDict];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(#"%#", responseObject);
} else {
NSLog(#"Error: %#, %#, %#", error, response, responseObject);
}
}] resume];
NSData *data = someData;
NSMutableURLRequest *requeust = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:[self getURLWith:urlService]]];
[reqeust setHTTPMethod:#"PUT"];
[reqeust setHTTPBody:data];
[reqeust setValue:#"application/raw" forHTTPHeaderField:#"Content-Type"];
NSURLSessionDataTask *task = [manager uploadTaskWithRequest:requeust fromData:nil progress:^(NSProgress * _Nonnull uploadProgress) {
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
}];
[task resume];
I'm using AFNetworking 2.5.3 and create new POST method for AFHTTPRequestOperationManager.
extension AFHTTPRequestOperationManager {
func POST(URLString: String!, rawBody: NSData!, success: ((AFHTTPRequestOperation!, AnyObject!) -> Void)!, failure: ((AFHTTPRequestOperation!, NSError!) -> Void)!) {
let request = NSMutableURLRequest(URL: NSURL(string: URLString, relativeToURL: baseURL)!)
request.HTTPMethod = "POST"
request.HTTPBody = rawBody
let operation = HTTPRequestOperationWithRequest(request, success: success, failure: failure)
operationQueue.addOperation(operation)
}
}
Please use below method.
+(void)callPostWithRawData:(NSDictionary *)dict withURL:(NSString
*)strUrl withToken:(NSString *)strToken withBlock:(dictionary)block
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
Please use below method.
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:[NSString stringWithFormat:#"%#/%#",WebserviceUrl,strUrl] parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:#"timeoutInterval"] longValue];
[req setValue:strToken forHTTPHeaderField:#"Authorization"];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
if ([responseObject isKindOfClass:[NSData class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
if ((long)[httpResponse statusCode]==201) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:#"201" forKey:#"Code"];
if ([httpResponse respondsToSelector:#selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
NSLog(#"%#",[dictionary objectForKey:#"Location"]);
[dict setObject:[NSString stringWithFormat:#"%#",[dictionary objectForKey:#"Location"]] forKey:#"Id"];
block(dict);
}
}
else if ((long)[httpResponse statusCode]==200) {
//Leave Hours Calculate
NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
block(serializedData);
}
else{
}
}
else if ([responseObject isKindOfClass:[NSDictionary class]]) {
block(responseObject);
}
} else {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:ServerResponceError forKey:#"error"];
block(dict);
}
}] resume];
}

How to upload large size of file by using AFNetworking

I'm working on an app in which I need to upload file to some server, and I'm using AFNetworking to upload file.
All work fine except if file size is short like 2mb and if more than this, server respond me error with status code 500 and doesn't upload file.
Here below is code how I am uploading.
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:lang forHTTPHeaderField:#"Accept-Language"];
[request setValue:authVal forHTTPHeaderField:#"authorization"];
[request setValue:[headerParams objectForKey:#"x-file-name"] forHTTPHeaderField:#"x-file-name"];
[request setValue:[headerParams objectForKey:#"x-convert-document"] forHTTPHeaderField:#"x-convert-document"];
[request setValue:[headerParams objectForKey:#"x-source"] forHTTPHeaderField:#"x-source"];
//convert parameters in to json data
if ([params isKindOfClass:[NSDictionary class]]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
[request setURL:[NSURL URLWithString:action]];
[request setTimeoutInterval:200.0];
[request setHTTPMethod:#"POST"];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:imageData];
NSLog(#"File size is : %.2f MB",(float)imageData.length/1024.0f/1024.0f);
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSInteger statusCode = [operation.response statusCode];
NSNumber *statusObject = [NSNumber numberWithInteger:statusCode];
successBlock(responseObject, statusObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}
The line of code [request setHTTPBody:imageData]; is setting NSData of image.
The same thing works on Android and its working fine but they'r using stream, first to write file into Physical path then by using stream to upload. Is this possible by using AFNetworking? or can I achieve this by using other approach too?
Looking for Suggestion.
Thanks
Note :- I have just implemented Image Upload service using AFNetworking 3.0,
-> Here kBaseURL means Base URL of server
->serviceName means Name of Service.
->dictParams means give parameters if needed, otherwise nil.
->image means pass your image.
Note :- This code written in NSObject Class and we have apply in our Project.
+ (void)requestPostUrlWithImage: (NSString *)serviceName parameters:(NSDictionary *)dictParams image:(UIImage *)image success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure {
NSString *strService = [NSString stringWithFormat:#"%#%#",kBaseURL,serviceName];
[SVProgressHUD show];
NSData *fileData = image?UIImageJPEGRepresentation(image, 0.5):nil;
NSError *error;
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:#"POST" URLString:strService parameters:dictParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if(fileData){
[formData appendPartWithFileData:fileData
name:#"image"
fileName:#"img.jpeg"
mimeType:#"multipart/form-data"];
}
} error:&error];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(#"Wrote %f", uploadProgress.fractionCompleted);
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
[SVProgressHUD dismiss];
if (error)
{
failure(error);
}
else
{
NSLog(#"POST Response : %#",responseObject);
success(responseObject);
}
}];
[uploadTask resume];
}
--> Now apply in our project.
UIImage *imgProfile = //Pass your image.
[WebService requestPostUrlWithImage:#"saveImageWithData" parameters:nil image:imgProfile success:^(NSDictionary *responce) {
NSString *check = [NSString stringWithFormat:#"%#",[responce objectForKey:#"status"]];
if ([check isEqualToString: #"1"]) {
//Image Uploaded.
}
else
{
//Failed to Upload.
}
} failure:^(NSError *error) {
//Error
}];

AFNetworking2 send parameter as query string in POST request?

I need to send query string in URL as well as JSON in body while making POST request.To send query string in url i override HTTPMethodsEncodingParametersInURI property as suggested in this thread on SO like
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:fullUrl]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:#[#"POST", #"GET", #"HEAD", #"PUT", #"DELETE"]];
[manager POST:fullUrl parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
but it seems doing this add my JSON data into URL as well, hence my request is not executed on server.But i need to send only 'command' parameter into url and some JSON data into request body.
my fullUrl string is looks like http://some_ip_address/config?command=some_command and param is NSDictionary object.
Note that there is a parameter in fullUrl i.e. command and i also send a NSDictionary object as param in
[manager POST:fullUrl parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Edit2: I also tried with NSURLSession
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://my_server_ip/config?command=plugs"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:0 error:&error];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}];
[postDataTask resume];
but get status code: 400 in NSURLResponse.
Edit3: someone suggested to subclass AFHTTPRequestSerializer class in this SO thread so i tried with
#implementation CustomAFHTTPRequestSerializer
-(id)init
{
self = [super init];
return self;
}
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
error:(NSError *__autoreleasing *)error
{
NSString* encodedUrl = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSError *error1;
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error1];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
return request;
}
#end
And assign it as requestSerializer of operationManager
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [[CustomAFHTTPRequestSerializer alloc] init];
But still get Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: bad request (400)
Please help me guys, Any help would be highly appreciated.

AFNetworking POST non JSON String

I am trying to create a POST request by using AFNetworking library.
[self.manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id response)
{
// CODE
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
// CODE
}];
Is there a way to post a simple string (not a JSON one) as a request body parameters by using AFNetworking?
Yes this is how you do it:
NSString *someString = #"SomeString";
NSData* stringData = [someString dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"someUrlString"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: stringData ];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//Success Block
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure Block
}];
[op start];

POST JSON string in request body (not in URL-Form-Encoded Request) AFNetworking

I want to send a JSON String to server using AFNetworking POST request.
Currently I am trying following code
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSData * data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
[request setTimeoutInterval:120];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject)
{ NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
[operation start];`
Nothing is happening. The code neither enters success block nor the failure block. What can be the reason? Is there any alternate way of doing this in AFNetworking 2.
NOTE: Request is working perfectly on POSTMAN and returns response in less than 500 ms.
This is working code of mine
NSDictionary *parameters = [NSDictionary dictionary];//set values here
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
[manager POST:#"http://example.com/api" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//Do success code
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//do failure code
}];
This is the function which configure HTTP body AFJSONRequestSerializer
#pragma mark - AFURLRequestSerialization
- (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];
}
}];
if (parameters) {
if (![mutableRequest valueForHTTPHeaderField:#"Content-Type"]) {
[mutableRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
}
[mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
}
return mutableRequest;
}
You are using AFJSONRequestSerializer as request serializer and it is meaning, you are sending JSON string from NSDictionary as HTTP body
[mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
}
So you all need to do is make NSDictionary from JSON values, and call as above.
No need to make JSON string.

Resources