I have the following code below that uses a rather old library called ASIHTTPRequest. I am looking to upgrade the library, but need a little help to make sure I am doing it correctly and to get my feet wet. This is the code I need to convert to AFNetworking. Any tips or suggestions is appreciated.
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 setUserAgentString:USER_AGENT];
[request setTimeOutSeconds:60];
[request addRequestHeader:#"apiKey" value:apiKey];
[request setRequestMethod:method];
With AFNetworking the code should look like below
NSDictionary *parameters=#{"key":value};//The values you want to POST arrange in dictionary.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:apiKey forHTTPHeaderField:#"apiKey"];
[manager.requestSerializer setValue:USER_AGENT forHTTPHeaderField:#"User-Agent"];
[manager.requestSerializer setTimeoutInterval:60];
[manager POST:urlStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Result %#",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error.description);
}];
I hope it helps. Cheers.
Related
Im trying to send some json data to a http server in my ios app, but I dont know how to verify if data got there... For testing Im using http://www.jsontest.com/.
NSURL *url = [NSURL URLWithString:#"http://validate.jsontest.com"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:createJson()]; //createJson() is my function which pass json data
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"http://validate.jsontest.com"]]; //by this I want to open json site in browser and see if data come. - but something different should be here I guess
So... How should I change my code to see data from createJson() in browser? Are there any mistakes in code so data arent even sent to a server?
Thank you for any help.
I recommend using AFNetworking
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
That you have 2 blocks one runs on success & other on failure.
This is the link on Github
https://github.com/AFNetworking/AFNetworking
So - I have identical AFNetworking code, that, when run on the simulator, returns results as expected, and gives me all the proper JSON back.
Soon as I run it on the device, I get a 401. Now, I understand this means 'unauthorized,' but how on earth does it run absolutely swimmingly on the simulator and then give me a 401 on the device?
The code is below and has only been changed to remove the address of our API which must remain private.
phoneNumber = phoneNumberField.text;
[[NSUserDefaults standardUserDefaults] setObject:phoneNumber forKey:#"phone_number"];
NSString *UDIDstring = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSLog(#"UDID: %#",UDIDstring);
NSString *jsonRequest = [NSString stringWithFormat:#"{\"userId\":\"%#\",\"userType\":\"%#\",\"deviceId\":\"%#\",\"deviceType\":\"%#\"}",phoneNumberField.text,#"Number",UDIDstring,#"iPhone"];
NSLog(#"json: %#",jsonRequest);
NSDictionary *stuff = [[NSDictionary alloc] initWithObjectsAndKeys:
phoneNumberField.text, #"userId",
#"Number", #"userType",
UDIDstring,#"deviceId",
#"iPhone",#"deviceType",
nil];
NSLog(#"stuff: %#",stuff);
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:stuff options:0 error:&error];
NSString *urlString = #"(hidden for privacy reasons)"
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
NSString *userpass = [#"vclient:VastV1" base64EncodedString];
NSLog(#"userpass: %#",userpass);
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"Basic: %#",userpass] forHTTPHeaderField:#"Authorization"];
//[request setValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
securityPolicy.allowInvalidCertificates = YES;
op.securityPolicy = securityPolicy;
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON responseObject: %# ",responseObject);
[infoLabel setText:#"You have been sent an activation code to the number you used. Please enter it above."];
[signupLabel setText:#"your code:"];
[mainButton setTitle:#"Activate" forState:UIControlStateNormal];
firstSignup=true;
[phoneNumberField setText:#""];
[phoneNumberField setPlaceholder:#"Enter activation code."];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error localizedDescription]);
}];
[op start];
One difference would be that you are reporting a different device ID. Maybe the API that you are using keeps track of device IDs that have been authorized. And your Mac has been authorized, but the iOS device hasn't.
You could try logging the device id on the Mac, and then change your code to use that ID as a hardcoded string, instead of using what the iPhone returns.
You can try this, I do it all the time
#import "AFNetworking.h"
NSDictionary *params = #{ #"key1": txtBox1.text, #"key2", txtbox2.text};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFJSONRequestSerializer *serializerRequest = [AFJSONRequestSerializer serializer];
AFJSONResponseSerializer *serializerResponse = [AFJSONResponseSerializer serializer];
[serializerRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"]];
serializerResponse.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
manager.requestSerializer = serializerRequest;
manager.responseSerializer = serializerResponse;
[manager.securityPolicy setAllowInvalidCertificates:YES];
[manager POST:#"url"
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
// DO WHAT YOU WANT IF SUCCESSED
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// DO WHAT YOU WANT IF FAILED
}];
Are you using an authentication scheme that depends on the time? I've seen drift on the simulator that causes it to 401.
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.
First calling for "post method" its working fine using AFHTTPRequestOperationManager. But second time i called get method for same AFHTTPRequestOperationManager got EXC_BAD_ACCESS. Please check my below source and help how to resolve.
FIRST CALLING "POST" METHOD- WORKING FINE
NSString *post =[[NSString alloc] initWithFormat:#"grant_type=client_credentials"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest
alloc] init];
[request setURL:[NSURL URLWithString:#"https://example.com/oauth/token"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"enctype"];
[request setValue:#"xxxxxxxxxx"] forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"enctype"];
[request setHTTPBody:postData];
[request setTimeoutInterval:120];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = YES;
[manager.requestSerializer setTimeoutInterval:120];
[post release];
AFHTTPRequestOperation *operation2 = [[AFHTTPRequestOperation alloc] init];
operation2 = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
NSHTTPURLResponse *response = (NSHTTPURLResponse *)operation.response;
NSLog(#"Response: %#", operation.responseString);
NSLog(#"%ld", (long)response.statusCode);
NSData* data=[operation.responseString dataUsingEncoding:NSUTF8StringEncoding];
NSString *response1 = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding: NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:#"check_auth_token_init" object:[[ResponseHandler instance] parseToken:response1]];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", operation.responseString);
}];
[operation2 start];
SECOND CALLING "GET" METHOD- EXC_BAD_ACCESS
NSMutableURLRequest *request = [[NSMutableURLRequest
alloc] init];
[request setURL:[NSURL URLWithString:#"https://example.com/stu/groups/"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"testing" forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//Here i tried to internalize "AFHTTPRequestOperationManager" but im getting EXC_BAD_ACCESS Please check attached screen shots
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
manager.securityPolicy.allowInvalidCertificates = YES;
// Configure Request Operation Manager
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];
// Send Request
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", operation.responseString);
}];
[operation start];
The warning "Method possibly missing a [super dealloc] call" suggests that you're compiling AFNetworking without ARC, which would explain why objects are being prematurely deallocated.
Please follow the installation instructions provided in the AFNetworking README to ensure that everything is configured correctly.
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?