Firstly I tried the same web service with advanced rest client. it works fine. but i am having difficulty writing the equivalent in afnetworking.
here is the Webservice.
http://devmybartersite.pantheon.io/myrestapi/barter_user/create?str= {"email":"sahildgfdffdfduuy#gmail.com","pass":"hello"}
i am able to get the response in advanced rest client in chrome. Additionally need to set a X-CSRF-Token in the header.
Here is my code
- (IBAction)pressed:(id)sender {
NSLog(#"You entered %#",self.username.text);
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//header fields
[manager.requestSerializer setValue:#"vZu-YUFWLzIdFIn7VDoA6hV9IhrYe-BimkC1ncRdojU" forHTTPHeaderField:#"X-CSRF-Token"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSDictionary *params = # {#"user":#"kjhkhkjhmnbbnjhio#gmail.com", #"pwd":#"hello" };
[manager POST:#"http://dev-my-barter-site.pantheon.io/myrestapi/barter_user/create" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
Default requestSerializer will transform your parameters to the following format user=kjhkhkjhmnbbnjhio#gmail.com&pwd=hello. In order to get JSON formatted request body, use AFJSONRequestSerializer:
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"..." forHTTPHeaderField:#"..."];
[manager.requestSerializer setValue:#"..." forHTTPHeaderField:#"..."];
than you send request:
[manager POST:....]
Related
i tried it but didn't work in AFNetworking only showing parameters error
but i used postman to check and when i send data via key and value it showing error but from raw data i send {"register_id":"3"}
then it will show me data so how to post parameter like this in AFNetworking.
using This Link
http://www.icubemedia.net/visitorbook/display_all.php
is any one can help me for that how to post that data
log error is:
2015-06-19 14:05:08.078 DemoAFNetworking[72771:1160924]
{"msg":"parameter missing!"}
Indeed there are no parameters missing, the fact that the request worked in Postman was the key. On the one hand, you should be trying to POST to that URL, not GET. On the other hand, since you are sending a JSON, you need the appropriate serializer.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//JSON Serializer
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = #{#"register_id": #"3"};
[manager POST:#"http://www.icubemedia.net/visitorbook/display_all.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
Check this example on how to do a GET with simple parameter with AFNetworking 2.0:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
NSDictionary *parameters = #{#"foo": #"bar"};
[manager GET:#"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
EDIT 1: added JSON serializer ;)
NSDictionary *parameters = #{
#"project_name": #"hasanProj",
#"project_desc" : #"testing...",
#"project_date" : #"2015-2-22"
};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:#"http://serverIP"]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:[HRUser sharedUser].userApiKey forHTTPHeaderField:#"Authorization"];
[manager POST:#"/rest/v1/project" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error: %#",error.localizedDescription);
}];
This code is returning Request failed: bad request (400).
I checked parameter, url they are all correct. I called it from chrome extension postman and getting correct result.
And other requests are working perfectly, even get is working fine.
But why I am getting Request failed: bad request (400) on this?
I was also facing the same error and this worked for me..
manager.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndex:400];
or
You can directly parse the response object.
i think there will be problem with the request. your putting wrong type or wrong data.
acceptableContentTypes for request also matters.
second thing the parameters that your sending data to it. check tags correct are not
ask WEB service developer exact need of API.
Code:
NSDictionary *parameters = #{
#"project_name": #"hasanProj",
#"project_desc" : #"testing...",
#"project_date" : #"2015-2-22"
};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]init];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.requestSerializer setValue:[HRUser sharedUser].userApiKey forHTTPHeaderField:#"Authorization"];
[manager.requestSerializer.acceptableContentTypes setByAddingObject:#"application/json"];
[manager.responseSerializer.acceptableContentTypes setByAddingObject:#"application/json"];
[manager POST:#"http://serverIP/rest/v1/project" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"error: %#",error.localizedDescription);
}];
I am using AFNetworking to post a username and password, so that I can get a JSON response.
I am readily getting JSON response in POSTMAN client as in below snapshot :
But then, whenever I hit the same URL with the AFNetworking library :
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:urlString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
The error I get is as below :
I even tried adding the below code, but it always gave the same error response :
AFHTTPRequestSerializer *serializerRequest = [AFHTTPRequestSerializer serializer];
[serializerRequest setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
manager.requestSerializer = serializerRequest;
manager.responseSerializer = [AFJSONResponseSerializer serializer];
How can I get the JSON response as in the postman client.
Any kind of help is appreciated.
If the HTTP Response code 401 is not in your acceptableStatusCodes list. AFNetworking will not proceed to deserialise the object. But instead create an NSError object which is what you are seeing outputted.
This functionality can be found AFURLResponseSerialization.m:132.
If you would like to update the HTTP codes you wish to accept you can use:
self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 200)];
Otherwise if you are confident that the request contains JSON body, you can still access the data from the NSError that is produced as its contained in the userInfo with the key
AFNetworkingOperationFailingURLResponseErrorKey and deserialise it manually.
More information: https://github.com/AFNetworking/AFNetworking/issues/2410#issuecomment-63304245
I'm working on a mobile app that takes personal information from users then saves it to the php server. I'm having a problem on the data with array of dictionaries, how do I fix this?
The sample data that the mobile app sends to the server looks like this, see the work_experience, it's an array of dictionaries:
Don't mind the data values, it's taken on different times, mind the data structure in work_experience
It becomes like this when it reaches the server:
This is how the work_experience gets saved, which is wrong:
This is my post request:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:SAVE_USER_INFO_URL parameters:_userInformation success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
php function that receives the post request:
$params = $this->params()->fromPost();
$userId = $this->getUsersTable()->saveUserInfo($params);
$this->getSkillsTable()->saveSkills($params['skillset'], $userId);
$this->getWorkExperienceTable()->saveWorkExperience($params['work_experience'], $userId);
$view = new JsonModel($params);
return $view;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
//manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:SAVE_USER_INFO_URL parameters:_userInformation success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
You are limiting the app to only accept responses with header text/html, which is not correct because you are looking for json response. And you need to set the requestSerializer to a AFJSONRequestSerializer instance because the default is AFHTTPRequestSerializer
I would like to make the following request from my app:
AFHTTPRequestOperationManager *requestManager = [[AFHTTPRequestOperationManager alloc] init];
requestManager.responseSerializer.acceptableContentTypes = [requestManager.responseSerializer.acceptableContentTypes setByAddingObject:#"application/json"];
requestManager.requestSerializer = [AFJSONRequestSerializer serializer];
[requestManager POST:urlString parameters:aParameters constructingBodyWithBlock:nil success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"%#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(#"error: %#", error);
}];
Where aParameters is an NSDictionary with the following content:
NSDictionary *urlParams = #{#"username" : anUser.userName, #"password" : anUser.password};
When I make the request from my app with the user input of "anUsername" and "aPassword" I get the following log for the body in my servlet:
--Boundary+5738A89B2C391231
Content-Disposition: form-data; name="password"
aPassword
--Boundary+5738A89B2C391231
Content-Disposition: form-data; name="username"
anUsername
--Boundary+5738A89B2C391231--
multipart/form-data; boundary=Boundary+5738A89B2C391231
I was under the impression that using AFJSONRequestSerializer would send my request in the appropriate format, but as the log shows, it's multipart/form data. It is really hard (for me) to parse this kind of request (I'm parsing it in Java on the server side), so my question is: is it possible to send a json in the body of my request? Something like this:
{
"userName" : "anUsername",
"password" : "aPassword"
}
Any help would be appreciated.
For anyone concerned: Instead of using the POST:parameters:constructingBodyWithBlock:success:failure: method, you should use POST:parameters:success:failure:. The former performs a multipart form request, while the latter does url form encoding. Additionally, to send the params in JSON, the requestSerializer property of the AFHTTPRequestOperationManager instance should be an instance of AFJSONRequestSerializer (by default it is set to AFHTTPRequestSerializer)
It is really helpful to browse the implementation file of AFHTTPRequestOperationManager for details, it helped me sort this error out.
You don't need to send pure JSON in POST request, just send Parameters dictionary. Here is the sample code that is working for POST Request.
+ (void)login:(BOUser *)user responseBlock:(APIRequestResponseBlock)responseBlock {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"parse-application-id-removed" forHTTPHeaderField:#"X-Parse-Application-Id"];
[manager.requestSerializer setValue:#"parse-rest-api-key-removed" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.securityPolicy.allowInvalidCertificates = YES;
NSString *URLString = [NSString stringWithFormat:#"%#login", BASE_URL_STRING];
NSDictionary *params = #{#"email": user.username,
#"password": user.password};
[manager POST:URLString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
responseBlock(nil, FALSE, error);
}];
}
I hope it helps.