AFNetworking read text/html as html and not JSON - afnetworking

I am using AFNetworking and making a request to my server. Ideally my server returns JSON (with the correct content-type=application/json header) But sometimes something bad happens and POST request just returns raw html. When this happens I just want to read the html as a string. The problem is that it I can't get AFNetworking to deal with anything that isn't json or xml. I already added text/html to set of acceptedContentTypes.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:KIWI_URL parameters:postParams success:^(AFHTTPRequestOperation *operation, id objects) {
NSLog(objects);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"10error: %#", error);
}];

You can do this by changing responseSerializer. After manager initialization add this code:
manager.responseSerializer = [AFCompoundResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
In success block you can read the response using:
NSLog(#"RESPONSE:\n%#", [[NSString alloc] initWithData:responseObject encoding:1]);

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

AFNetworking unable to serialize gzipped response (response object is nil)

I'm using AFNetworking to download a .gzip file, that when uncompressed should return a JSON string. I've made the get request via my browser, the .gzip file is downloaded and when unzipped, the appropriate JSON is retrieved.
I know AFNetworking is built on NSURLConnection, and from what I read NSURLConnection has gzip inflation in built into it. However, I'm unable to uncompress and parse the gzip file returned by the server into JSON. The response object from AFNetworking remains nil. My code is as follows:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/plain", #"application/x-gzip", nil];
[manager GET:[NSString stringWithFormat:#"%#%#", BASE_URL, GET_CONTENTS_URL] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
if(responseObject == nil){
NSLog(#"Response is still nil");
}
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
I'm unsure why this does not work.
Note 1: However, if I replace the response serializer to AFHTTPResponse serializer, the response object is not nil. However, it is of class _NSInlineData, which is an undocumented class.
I had the same problem, Finally I get work with the help of AFgzipRequestSerializer.
You need to use "AFgzipRequestSerializer".
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFgzipRequestSerializer serializerWithSerializer:[AFJSONRequestSerializer serializer]];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
In my case, I use AFHTTPSessionManager and it worked fine without using AFgzipRequestSerializer to decode the response.

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