AFNetworking: Get JSON Value From Http Response - ios

I am primarily an android developer and really new to IOS. I am using AFNetworking 1.0 since I am working with an existing source and I am sending a standard http Post request and returning the data like so:
//Sending the post request and getting the result
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://testsite.org/mobile_app"]];
[httpClient setParameterEncoding:AFFormURLParameterEncoding];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"POST"
path:#"http://testsite.org/mobile_app/studentregister.php"
parameters:#{#"username":username, #"displayname":displayname, #"password":password, #"passwordc":passwordc, #"email":email, #"teacherCode":teacherCode}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// Print the response body in text
NSLog(#"Response: %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];
the response should contain the JSON data which looks like this according to burp suit:
{"userCharLimit":"Your username must be between 5 and 25 characters in length"}
{"displaynameCharLim":"Your displayname must be between 5 and 25 characters in length"}
{"passLimit":"Your password must be between 8 and 50 characters in length"}
{"emailInvalid":"Not a valid email address"}
{"teacherCodeLength":"Your teacher code is not 5 to 12 characters"}.
How can I get those JSON values? I have seen a lot of AFNetworking 2.0 JSON examples and sending JSON Post request but I can seem to find much for version 1.0 let alone getting the values form a standard post request.
Any ideas or resources?

All you should need is to change your code to register a AFJSONRequestOperation instead of AFHTTPRequestOperation.
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
Then you can use this method on AFHTTPClent to create the operation which will actually be of type AFJSONRequestOperation.
AFHTTPRequestOperation *operation = [httpClient HTTPRequestOperationWithRequest:request success:nil failure:nil];
[httpClient enqueueOperation:operation];

Related

AFNetworking http basic authentication gives error "Your API key was not formatted properly"

Trying to use the postmates api, but running into issues with authorization.
To quote their site:
AUTHENTICATION
The Postmates API requires authentication by HTTP Basic Auth headers.
Your API key should be included as the username. The password should
be left empty.
The actual header that is used will be a base64-encoded string like
this:
Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==
I tried using AFNetworking like so
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSURLCredential *credential = [NSURLCredential credentialWithUser:#"(my postmates key)" password:#"" persistence:NSURLCredentialPersistenceNone];
NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:#"GET" URLString:#"https://api.postmates.com/v1/delivery_zones" parameters:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCredential:credential];
[operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
[manager.operationQueue addOperation:operation];
The error message I'm getting is
Incorrect NSStringEncoding value 0x0000 detected. Assuming NSASCIIStringEncoding. Will stop this compatiblity mapping behavior in the near future.
Success: {
code = "invalid_authorization_header";
kind = error;
message = "Your API key was not formatted properly";
}
Instead of creating a credential, you might want to try:
[request setValue:#"Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==" forHTTPHeaderField:#"Authorization"];

IOS sending post method data can access in php as get method

I am very new to iOS. I am trying to send data through post method to PHP. In PHP it can't take data like $_POST['data'], but it takes $_GET['data']. My iOS code is as follows.
NSString *strURL = [NSString stringWithFormat:#"http://example.com/app_respond_to_job?emp_id=%#&job_code=%#&status=Worker-Accepted&comment=%#",SaveID2,txtJobcode1,alertTextField.text];
NSURL *apiURL = [NSURL URLWithString:strURL];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:apiURL];
[urlRequest setHTTPMethod:#"POST"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
_receivedData = [[NSMutableData alloc] init];
[connection start];
NSLog(#"URL---%#",strURL);
Can someone explain why is that, it will be very helpful.
Please Download this file https://www.dropbox.com/s/tggf5rru7l3n53m/AFNetworking.zip?dl=0
And import file in your project
Define in #import "AFHTTPRequestOperationManager.h"
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:#"Your Url"]];
NSDictionary *parameters = #{#"emp_id":SaveID2,#"job_code":txtJobcode1.text,#"status":alertTextField.text};
AFHTTPRequestOperation *op = [manager POST:#"rest.of.url" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %# ***** %#", operation.responseString, responseObject);
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[responseObject valueForKey: #"data"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %# ***** %#", operation.responseString, error);
}];
[op start];
because you send your data via query string in url
i think it will work if you try to pass data in your request's body:[urlRequest setHTTPBody:...]
POST parameters come from the request body, not from the URL string. You'll need to:
Call setHTTPBody on the request and provide the URL-encoded string (sans question mark, IIRC) as the body data
Call setValue:forHTTPHeaderField: to set the Content-Type to application/x-www-form-urlencoded
Either remove the call to [connection start] or use initWithRequest:delegate:startImmediately: so that you aren't starting the connection twice.
That last one is kind of important. You can get strange results if you try to start a connection twice. :-)

AFNetworking 2.0 and GET Request parameters

I have a question about AFNetworking 2.0
I have to make a GET request like this:
http://myhost.come/entity?language=en&query=$UserId=14 and $EntityCreationDate>'2014-09-01'
How to generate the Dictionary parameters for this request?
In particular I not understand how can I build this: and $EntityCreationDate>'2014-09-01'
Here I found a good tutorial.
Which states a simple GET request can be sent like this:
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://samwize.com/"]];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"GET"
path:#"http://samwize.com/api/pigs/"
parameters:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
// Print the response body in text
NSLog(#"Response: %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];

SDK and AFNetworking

I am trying to write code for an SDK. I need to make API calls.
I am using AFNetworking 2.0 to send a POST request to the server:
NSDictionary * params = [self formDictionaryFromCard: card];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString: [self apiUrl] parameters: params];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"Firefox" forHTTPHeaderField:#"User-Agent"];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
successBlock(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
errorBlock(error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
So far I have the above, but I can't figure out how to pass in headers (like the authorization header), or provide support for https.
Can anyone please help?
Also how can I know what http status code was returned?

AFNetworking Post request not working

I am facing a problem in making a POST request to a .net webservice method.
I have made a lot of post request but i just don't seem to get the problem i am facing here
The request is made successfully with the help of Rest client
But it always gives me a 400 error
I am using AFNetworking to make the post request
Please find the code below if something is wrong
NSURL *url=[NSURL URLWithString:#"http://WebService.svc"];
NSMutableDictionary *params=[NSMutableDictionary dictionary];
[params setValue:#"cabbage123" forKey:#""];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient postPath:[NSString stringWithFormat:#"Users/%#",userId] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Print the response body in text
NSLog(#"Response: %#",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
And i get a html response with this error
AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest http://WebService.svc/Users/userid>, NSErrorFailingURLKey=http://WebService.svc/Users/userid, NSLocalizedDescription=Expected status code in (200-299), got 400, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x7ba6df0>}
I think there is some problem with AfNetworking for WCF web-services.
Ultimately i could connect and use the web-service by using the standard NSURLConnection class. Though i am facing the same problem for PUT request now.
Have you tried to setup AFNetworking to allow invalid certificates?
httpClient.allowsInvalidSSLCertificate = YES;
of if you want to use operations.
AFSecurityPolicy *sec=[[AFSecurityPolicy alloc] init];
[sec setAllowInvalidCertificates:YES];
operation.securityPolicy=sec;

Resources