Synchronous NSURLConnection https post request with JSON - ios

I need to make a HTTPS post request to a server using a synchronous connection. I've made plenty of http connections but for some reason the code doesn't work with https and I'm sure the website address is right.
Some of my code:
Note that dparam is a dictionary object.
NSError *err;
NSData *parameterJSONData = [NSJSONSerialization dataWithJSONObject:dparam options:
NSJSONWritingPrettyPrinted error:&err];
NSString *param = [[NSString alloc] initWithData:parameterJSONData encoding:NSUTF8StringEncoding];
NSString *post =[[NSString alloc] initWithFormat:#"varnameOne=%#&varnameTwo=%#&param=%#",vone,vtwo,param];
//my_url is a string defined elsewhere
NSURL *url=[NSURL URLWithString:my_url];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
I need to do this synchronously as I don't really have the time to change all my database calls to asynchronous and the calls need to either complete or fail before the program continues so it'd have to be made effectively synchronous anyway.
That said I did try a synchronous route but it didn't work with https only http.

Related

no visible #interface for nsmutableurlrequest declares the selector sethttpbody

this is my screenshot[I searched for solution of this but did not get any solution. why it shows me an error displayed in screenshot. please help me.
NSURL *url=[NSURL URLWithString:#"http://www.gourmet7.com/auth"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
]2
It can only be a wild guess, but as your code compiles just fine, I think you're targeting some iOS version lower than 8.0.
Unfortunately, the HTTPBody property is only available since 8.0. So you either have to raise the minimum iOS version to at least 8.0 or use another mechanism.

How to send raw data to API

I have one text field I need to send two data's to API.
NSString *post =[NSString stringWithFormat:#"val1=%#,val2=%#",[[NSUserDefaults standardUserDefaults] objectForKey:#"val1"],val2];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://api.test.com/send"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"log%#",str);
}
I need to send only raw data to API this is my code.Please check and let me know thanks
NSData *postData = [someStringToPost dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:someURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%d", postData.length] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *response = nil;
NSData *retData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
if (error)
{
//error
}
else
{
//no error
}
Try this
Have you tried converting it to NSData and sending that?
Here's the conversion:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
That will give you the data in bytes, then just pass it in with the normal networking function calls.

IOS JSON sending an email from Mandrill

I have an IOS application that I would like to send an email via Mandrill. I have tried to implement this, but its not working and Ive confused myself.
When pressing the button to send an email from the IOS application I log this error message:
{"status":"error","code":-1,"name":"ValidationError","message":"You must specify a key value"}
My code is:
NSString *post = [NSString stringWithFormat:#"{\"key\": \"abcdefg123456\", \"raw_message\": \"From: me#mydomain.com\nTo: me#myotherdomain.com\nSubject: Some Subject\n\nSome content.}"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://mandrillapp.com/api/1.0/messages/send-raw.json"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"Post: %#", post);
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
Please let me know where I am going wrong.
It looks you forgot the \" after "content.".
Try to write your "post" variable as follow:
NSString *post = [NSString stringWithFormat:#"{\"key\": \"abcdefg123456\", \"raw_message\": \"From: me#mydomain.com\nTo: me#myotherdomain.com\nSubject: Some Subject\n\nSome content.\"}"];
I hope it helps.

Sending to PHP file on server using Post in iOS application

I am sending data to the php file on the server using post using following code
NSString *post =[[NSString alloc] initWithFormat:#"UserName=%#&UserPassword=%#",appDelegate.userName,appDelegate.userPassword];
NSLog(#"post is %#",post);
NSURL *url=[NSURL URLWithString:#"http://ec2-50-94-162-129.compute-1.amazonaws.com/usercredential.php?"];
NSLog(#"URL is %#",url);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
data = [data stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#",data);
This shows login Failed if I access directly file from browser and provide userNAme in address then it works fine it does not work from iPhone app

How to Use Cache Memory concept in objective-c

// Web service request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
//returndata is response of webservice
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue] ;
NSLog(#"chat data- %#",results);
NSString *strResults = [results objectForKey:#"d"];
NSLog(#"result string is-%#",strResults);
this is the code that I am using for my Data fetching from web service. But i have to do this every time when come to this page.
Is that any method that can store my data in Cache memory so i need not to request every time.
I Am using
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
but i dont know how to use - (NSCachedURLResponse *) connection this method
thanks...
You need to use cache as of your needs according to this documentation: whenever you requesting a NSMutableURLRequest...
For Ex:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:60];
For More details Kindly look into the Documentation

Resources