How to make post request with AFnetworking? - ios

I have to make a post request using AFNetworking library with following request parameters
{
"method":"validate",
"name":{
"firstname":"john",
"lastname":"doe"
}
}
How to make this request using latest version of AFNetworking v3 library?
I used the following code and it doesn't work
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
[manager setRequestSerializer:[AFJSONRequestSerializer serializer]];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
NSDictionary *parameters = #{\"method\":\"validate\",\"name\":{\"firstname\":\"john\",\"lastname\":\"doe\"}};
[manager POST:#"http://myUrl.." parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#",[responseObject description]);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"%#",[error localizedDescription]);
}];
Im getting the following error,
2016-02-13 11:04:54.085 SlideOutMenu[3698:50453] nulllllll
2016-02-13 11:04:55.794 SlideOutMenu[3698:50453] Failure Request failed: internal server error (500)
2016-02-13 11:04:55.795 SlideOutMenu[3698:50453] (null)

As you've already applied [manager setRequestSerializer:[AFJSONRequestSerializer serializer]] no need to convert dictionary to JSON again.
simply pass dictionary as a parameters, it will work.
NSDictionary *name = #{#"firstname": #"john", #"lastname": #"doe"};
NSMutableDictionary *parameters = [NSMutableDictionary new];
[parameters setObject:#"validate" forKey:#"method"];
[parameters setObject:name forKey:#"name"];
Also no need to initialise NSURLSessionConfiguration with defaultSessionConfiguration, AFNetworking will automatically initialise that. Simply use [AFHTTPSessionManager manager].

Your code is fine.Connect with your server guy.
code 500 is server side error.
check out this link for response code detail
http://www.restapitutorial.com/httpstatuscodes.html

Related

AFNetworking 3.0 Send Request Body content [duplicate]

This question already has answers here:
afnetworking 3.0 Migration: how to POST with headers and HTTP Body
(10 answers)
Closed 5 years ago.
I am working on a project that using AFNetworking to connect with API interface. My problem is that how to send a request to the backend with body content that includes email, deviceId. I have found many solutions that all compatible with AFNetworking 2.0 not 3.0.
Now I am using SessionManager, when i initialize request, how can I add content body context?
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
NSString *stringData = [[NSString alloc]initWithData:jsonData encoding:NSASCIIStringEncoding];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/html", nil];
[manager POST:_urlString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSString *link = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"JSON: %#",link);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
I have tried to put email& deviceId into [manager POST parameter: Dict], but it is not working.
Can someone tell me how to add body to AFNetworking 3.0? Thanks
if i got your question correctly it shouldnt be that hard. its similar to the 2.0 version as well.
NSDictionary *parameters = #{#"username": _username.text,
#"deviceId": deviceIdString,
};
NSMutableDictionary * parameters = [[NSMutableDictionary alloc]initWithDictionary:params];
NSURL *baseURL = [NSURL URLWithString:#"http://url.com/ws/test.php"];
AFHTTPSessionManager * manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
//Response
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(error.code==-1001){
//Handle the error
}
}];

AFNetworking 3.0 The data couldn’t be read because it isn’t in the correct format

There are other questions with similar titles but none of them helped me. I've to send a PUT request to server in order to change the status of appointment so I've made this method -(void)appointmentStatusChangedTo:(NSString *)statusID atAppointmentID:(NSString *)appointmentID In which I'm setting the URL and Parameters as
NSString *string = [NSString stringWithFormat:#"%#/API/Appointments/3",BaseURLString];
NSDictionary *para = #{
#"AppointmentStatusId":statusID,
#"ID":appointmentID
};
Then I've made URL request as
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"PUT" URLString:string parameters:para error:nil];
After that I'm setting the header for an authorization token as
NSString *token = [NSString stringWithFormat:#"Bearer %#",[[NSUserDefaults standardUserDefaults] objectForKey:#"userToken"]];
[req setValue:token forHTTPHeaderField:#"Authorization"];
So finally I'm calling it as
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error){
if (!error) {
if (response) {
NSLog(#"Respose Object: %#",responseObject);
[self.patientsAppointmentsTableView reloadData];
}
}
else {
// NSLog(#"Error: %#, %#, %#", error, response, responseObject);
NSLog(#"Error: %#", error.localizedDescription);
}
}] resume];
Now it is successfully sending the data to the server but as a response I'm getting
Error: The data couldn’t be read because it isn’t in the correct
format.
I am not sure what the response might look like at the moment as I'm not in contact with backend guy. But as far as I remember it was just a simple 1. SO kindly tell me how to handle any type of response using AFNetworking 3.0 or any change in my code.
try to use below code:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setStringEncoding:NSUTF8StringEncoding];
manager.requestSerializer=serializer;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
Try following code using Afnetworking 3.0
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:url parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"%#",responseObject);
self.responseHandlers(YES,responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
self.responseHandlers(NO,nil);
}];

How To Send NSData with AFNetworking 3 Without Using AFMultipartFormData

I am trying to send wav file as a NSData to rest service with AFNetworking 3. I figured out how to send with AFMultipartFromData but i got an error like that
errorMessage = "Can Not Map Content-Type String multipart/form-data; boundary=Boundary+02588C5 To Media Type ";
When i spoke with the guy who created rest service then he told me i have to send just NSData not anything like AFMultipartFormData. I need some help here because i could not find any way to send "just" NSData.
My code is below;
NSURL *URL = [NSURL URLWithString:#"http://xxxMyService"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = #{#"xx": #"yy ; zz"};
AFHTTPSessionManager *manager2 = [[AFHTTPSessionManager alloc] initWithBaseURL:URL sessionConfiguration:configuration];
manager2.responseSerializer = [AFJSONResponseSerializer serializer];
//I converted wav file to NSData
NSData *data=[self setVoiceRecordToNSData];
[manager2 POST:#"http://xxxMyService" parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:data name:#"data" fileName:#"Path.wav" mimeType:#"audio/wav"];
}
progress:nil success:^(NSURLSessionTask *task, id responseObject
{ NSLog(#"JSON: %#", responseObject);}
failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error); }];
Try add this code before POST
manager2.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"multipart/form-data"];

Having trouble sending requests using AFNetWorking

It seems that AFNetworking isn't working correctly for me. Specifically when I send apiKey request to server it gives me an unauthorized error. ASIHTTPRequest works fine for me however, so there seems to be something I am doing wrong in AFNetWorking. I know the problem is sending apiKey because if I comment it out AFNetWork works correctly. I still need to send the API key however. Any help will be appreciated.
AFNetWorking
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:apiKey forHTTPHeaderField:#"apiKey"];
NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] init];
[manager POST:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
[operation setUserInfo:userinfo];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[operation setUserInfo:userinfo];
}];
}
ASIHTTPRequest
NSString *urlStr = [NSString stringWithFormat:#"%#/%#", submitReportUrl, [self urlEncode:path]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setDelegate:self];
NSMutableDictionary *userinfo = [[NSMutableDictionary alloc] init];
[userinfo setObject:NSStringFromSelector(self.didFinishSelector) forKey:#"didFinishSelector"];
[userinfo setObject:NSStringFromSelector(self.didFailSelector) forKey:#"didFailSelector"];
[request setUserInfo:userinfo];
[request addRequestHeader:#"apiKey" value:apiKey];
[request setRequestMethod:method];
NSArray *keys = [params allKeys];
for ( NSString *key in keys )
[request addPostValue:[params objectForKey:key] forKey:key];
[self.operationQueue addOperation:request];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
I had the same problem working with the post. So research where was the problem. If you did not add the about line of the code. AFNetworking will automatically add in the header
Content-Type : "text/html"
either one
Cotent-Type : "text/plain"
By adding above code becomes
Content-Type : "application/json"
So the problem is solved. Since the server is expecting JSON.

AFNetworking 2.0 Send Post Request with URL Parameters

How do I send a POST request with AFNetworking 2.0 with all the parameters in the URL like such:
http://www.myserver.com?api_key=something&lat=2.4&radius=100
Right now I have:
NSString* query = #"http://example.com?name=param&date=param";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{};
[manager POST:query parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
But it's not working, I get this error back:
Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: bad request (400)
The previous best answer was to get the backend to change and accepts parameters in the body. Thats the preferred method but sometimes some of us are stuck using backends that can't change so I offer this solution....
In the class AFURLRequestSerialization there is a property called HTTPMethodsEncodingParametersInURI and that is an NSSet that contains the http methods that are allowed to use params in the uri GET, HEAD, and DELETE by default.
You could override that and include POST as well.
in AFURLRequestSerialization.m lines 462 has an if statement that checks self.HTTPMethodsEncodingParametersInURI property contains POST. if it doesn't (as it doesn't by default), it will put the parameters in the body.
You can comment out that id statement for a quick test.
To get it to work I recommend overwriting the HTTPMethodsEncodingParametersInURI property.
when setting up your AFHTTPSessionManager it should look like this...
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:self.httpBaseUrl]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.requestSerializer.HTTPMethodsEncodingParametersInURI = [NSSet setWithArray:#[#"POST", #"GET", #"HEAD", whatever other http methods you need here....]];
this should allow for sending a parameters in the uri of a POST. worked for me, hope it helps someone else
#import "AFNetworking.h"
...
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"param1": value1,
#"param2": value};
manager.responseSerializer = [AFJSONResponseSerializer serializer]; // if response JSON format
[manager POST:#"http://domain.com/backend.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}];
try this
I've had the same problem with you.
Other people's answers seem to be accurate.
The cause of the error is:
when you init NSUrl with parameters such as http:www.baidu.com/api?id=1&name=我,it needs you to encode your urlString with utf-8
such as :
//解决奇葩需求:请求方式为post时,url带?id=1之类。主要原因是url带中文的时候url初始化失败
URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
Hope to help you!
can you try this.
NSString* apiURL = #"http://example.com"
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:apiURL]];
manager.responseSerializer = [AFJSONResponseSerializer serilizer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
NSDictionary *parameters = #{#"name":#"John",#"date":"27/12/2013"};
AFHTTPRequestOperation *apiRequest = [manager POST:#"" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog#"response ---%#,responseObject";
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[apiRequest start];
I was able to do this by creating the string like this:
NSString *relativeURL =[NSString
stringWithFormat:#"/reward/commit?deviceUUID=%#&rewardID=%#",[[Client
sharedInstance] deviceUUID],self.rewardID];
and then passing it as the query. I had to set the requestSerializer and responseSerializer as follows:
client.requestSerializer = [AFJSONRequestSerializer serializer];
client.responseSerializer = [AFHTTPResponseSerializer serializer];
Worked for me once I left the manager.requestSerializer property alone and let it be the default (AFHTTPRequestSerializer).
The service i was POSTing to, was seemingly expecting UTF8 encoded body parameters.

Resources