how to test if json data got to a server ios - ios

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

Related

post json array to server in iOS?

i am trying to send json array data to server but it show the result is failed.
so plaese correct me where i did wrong.Here is code what i am using in this:
NSDictionary *dict=#{#"groupmembersarray":contactsArray};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *post = [NSString stringWithFormat:#"%#",jsonString];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://anaadit.net/caffe/newapp/AddGroupContact.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn==nil) {
NSLog(#"Connection could not be made");
} else {
responseData = [NSMutableData new];
NSLog(#"%#",responseData);
}
and nsurl connection delegate methods calling but the response is showing is nil .
so please check and correct me .Thanks in advance.
Use AFNetworking frame work instead, easy to use and implement.
https://github.com/AFNetworking/AFNetworking
POST request in AFNetworking -
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *dict=#{#"groupmembersarray":contactsArray};
manager.requestSerializer = [AFJSONResponseSerializer serializer];
[manager POST:#"http://anaadit.net/caffe/newapp/AddGroupContact.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
To set ant http header field you can use,
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
Please contact your webservice developer, he/she may have had some issue
Your question has been answered here: How to send POST and GET request?
Although judging from your comment, the issue isn't with the actual request but rather with the server. You wouldn't have gotten a response if your request code was faulty. You should check that the parameters are corresponding with what the server needs.
You can also check the status code of the request like so:
[(NSHTTPURLResponse*)response statusCode]

AFNetworking: How to convert this header request to use AFNetworking?

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.

EXC_BAD_ACCESS for AFHTTPRequestOperationManager

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.

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?

Translating from ASIHTTPRequest to AFNetworking , on iOS

What i want to do is post a json file to my server. I finally did that using ASIHTTPRequest and my code is :
NSURL *url = [NSURL URLWithString:#"http://foo.foo.foo"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"PUT"];
[request addRequestHeader:#"Authorization" value:#"Basic dslfkdsfdsflsdkfslkgflksflksdlfkg"];
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
NSLog(#"%#", [request responseString]);
What i need now is the exact above code translated to AFNetworking. Any ideas??
Thank you for reading my post :)
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://foo.foo.foo"]];
client.parameterEncoding = AFJSONParameterEncoding;
[client registerHTTPOperationClass:[AFJSONRequestionOperation class]];
[client setAuthorizationHeaderWithUsername:... password:...];
[client putPath:#"/path/to/resource" parameters:(_your JSON object as a dictionary_)
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", [request responseString]);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Resources