AFNetworking parse error when no content - ios

I am using AFNetworking to connect with API.
I have many request with json response.
In one case response is no content and I have go error serialization response.
self.manger.requestSerializer = [AFJSONRequestSerializer serializer];
[self.manger.requestSerializer setTimeoutInterval:15];
[self.manger POST:URL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
success(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
fail(operation,error);
NSLog(#"error code %d",[[[error userInfo] objectForKey:AFNetworkingOperationFailingURLResponseErrorKey] statusCode]);
}];

If you can't change server response (like Andy said, if you are expecting JSON response, server should reply with JSON), try to set response serializer to "standard" serializer, something like:
self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];

Related

how to make rest api call with afnetworking iOS

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:....]

how to post parameter like {"register_id":"3"} in AFNetworking

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 ;)

Error Code -1011 with status code 401

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

JSON text did not start with array Error with AFNetworking

I am using the below code to use perform a GET request. In reverse manner am sending the params into server and data storing in the server fine. But am getting the error
* JSON text did not start with array *
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"emails": emailid,
#"password": paswrd,
#"gender": gende,
#"firstname":name1,
#"lastname":firstname1,
#"dateofBirth":dob1,
#"Country":count
};
[manager GET:#"http://37.187.152.236:91/EmployeeSvc.svc/AddEmployee?"
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
-(void) testHTTPS {
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:[NSString stringWithFormat:#"%#", HOST] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
You can check your serve Content-Type,If is text/html,you need code this:
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
This problem can be due to bad JSON string. By Bad JSON string, I mean that your JSON response might not be starting with the expected characters i.e '[' or '{'. The starting characters must always be anyone of the above two.
Also there might be a chance that your JSON response is embedded in some kind of XML string. This happened to me and for me, it was just bad JSON response like I explained and I solved it by proper parsing.
Check this image. This is what bad JSON can look like.
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">
[{"Title":"DemoTitle","CreationDate":"06/06/2014","Description":"DemoDescription"}]
</string>
As you can see, JSON is embedded in XML string.**strong text**Also, check your JSON response on this site : http://jsonlint.com/
This will show you if the JSON you receive is valid for parsing or not.
Hope this helps.
This is the server side error when your server is not responding the JSON response OR Response is not a valid JSON because this error is appears when AF networking library unable to parse the JSON response.
Please check it with your server side about the response

AFNetworking 2.0: is it possible to put pure json in the body of a POST request?

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.

Resources