how to pass a dictionary using NSURLSession in post method? - ios

I do not know how to pass values in dictionary into server using NSURLSession via POST. Please help me to solve this problem.
My dictionary contains contact information (name and phone number only), where the key is the person's name and the value is their phone number.
I have sample code using nsurl connection - how can I convert it to use NSURLSession?
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://holla.com/login"]];
request.HTTPMethod = #"POST"; [request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"212333333",#"ABCD",#"6544345345",#"NMHG", nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
request.HTTPBody = jsonData;
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

I solve the problem by using the following method:
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL * url = [NSURL URLWithString:[ NSString stringWithFormat:#"http://xxxx.com/login/save_contact"]];;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys:#"212333333",#"ABCD",#"6544345345",#"NMHG",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
}];
[postDataTask resume];

Related

POSTING DATA TO A WS

I'm trying to post new data to a ws but im geting error each time
I need to
1-pass a username and password each time
2-code the data with AES256 WITH THE API KEY
Code:
- (IBAction)AddTicket:(id)sender {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSURL *URL = [[NSURL alloc] initWithString:#"http://dev.enano-tech.com/api/Ticket"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"1",#"id",#"1",#"idProject",#"1",#"idTicketType",#"nameo",#"name",#"nameo",#"description", #"1",#"idStatus",#"2016-06-23 15:20:49",#"creationDateTime", nil];
NSData *dataToPost = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSData *final =[dataToPost AES256EncryptWithKey:#"02b6e206868660a0d59d2e51a11fdcd6"];
//
NSLog(#"postData1e == %#",final);
NSLog(#"final %#",dataToPost);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
[request addValue:#"CURLAUTH_BASIC" forHTTPHeaderField:#"CURLOPT_HTTPAUTH"];
[request addValue:#"Basic YWRtaW46YWRtaW5hZG1pbg==" forHTTPHeaderField:#"authorization"];
[request addValue:#"admin:adminadmin" forHTTPHeaderField:#"CURLOPT_USERPWD"];
[request addValue:#"true" forHTTPHeaderField:#"CURLOPT_RETURNTRANSFER"];
[request addValue:#"false" forHTTPHeaderField:#"CURLOPT_SSL_VERIFYPEER"];
[request addValue:#"POST" forHTTPHeaderField:#"CURLOPT_CUSTOMREQUES"];
[request addValue:#"true" forHTTPHeaderField:#"CURLOPT_POST"];
[request addValue:#"false" forHTTPHeaderField:#"CURLOPT_POSTFIELDS"];
[request setHTTPBody:final];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *str = [[NSString alloc]initWithData:final encoding:NSUTF8StringEncoding];
NSLog(#"data %#",data);
NSLog(#"respoce %#",response);
NSLog(#"result == %#",result);
}];
[postDataTask resume];
}
Response:
2016-08-02 15:06:47.768 Projector[3936:1619429] result == {"error":"invalid API query", "message":"'data' is not correctly encoded for method POST. Request for correct API KEY"}
this is the documentation of api:
enter image description here
Your webserver is missing "data" from the website. To fix it, you'll need to add that field to your form or find the correct field name (case sensitive)

POST method resulting status code 400 ios

I have tried many times, but i cant do a simple POST request to a remote API.. I need to post username and password to get a login authorization. Here are the code:
NSURL * url = [NSURL URLWithString:#"http://thapi.xyz/auth/login"];
NSString *postData = #"username=emailExample#gmail.com&password=123456";
NSData * dataBody = [postData dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLenght = [NSString stringWithFormat:#"%d",[dataBody length]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-unlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLenght forHTTPHeaderField:#"Content-Lenght"];
[request setHTTPBody:dataBody];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(#" ERROR %#, RESPONSE %# AND DATA %#",connectionError,response,[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}];
I have made another version, witch uses NSDictionary and Json parsing (the API uses json)
NSDictionary * login = #{#"username":#"exampleMail#gmail",#"password":#"123456"};
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:login options:NSJSONWritingPrettyPrinted error:nil];
NSString *postLenght = [NSString stringWithFormat:#"%d",[jsonData length]];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-unlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLenght forHTTPHeaderField:#"Content-Lenght"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(#" ERROR %#, RESPONSE %# AND DATA %#",connectionError,response,[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}];
And here is the result of both codes:
2016-06-18 05:24:20.329 Hoffmann iOS[10317:1088208]
ERROR (null), RESPONSE <NSHTTPURLResponse: 0x796bee60>
{ URL: http://thapi.xyz/auth/login } { status code: 400, headers {
"Access-Control-Allow-Origin" = "*";
Connection = "keep-alive";
"Content-Length" = 70;
"Content-Type" = "application/json; charset=utf-8";
Date = "Sat, 18 Jun 2016 04:24:18 GMT";
Etag = "W/\"46-22Kcj8zTKrWgQ7OCr429+w\"";
Server = "nginx/1.6.2";
Vary = "Accept-Encoding";
"X-Powered-By" = undefined;
"X-Response-Time" = "5.357ms";
} } AND DATA {"name":"ParameterError","message":"Request should contain: username"}
I really appreciate all answers, and sorry for my bad english...
Perhaps the misspelling of the header variable is the issue ("Content-Lenght" is misspelled):
[request setValue:postLenght forHTTPHeaderField:#"Content-Length"];
NSURLConnection is deprecated. use nsurlsession instead Try this code....
//replace the following code with your request params
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *clientSessionId = [prefs stringForKey:#"clientSession"];
NSString *bodyString = [NSString stringWithFormat:#"[\"%#\",{\"session_token\":\"%#\",\"request\":[\"GetUnitDetails\",{}]}]",clientSessionId,clientSessionId];
//Make mutable url request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[Settings getMobileUrl]]];
NSData *postData = [bodyString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
//Change the http method as per your own choice
[request setHTTPMethod:#"POST"];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *connectionError)
{
if ([data length] > 0 && connectionError == nil)
{
NSError *localError = nil;
self.parsedObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&localError];
NSString* unitResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [unitResponse dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
}else {
NSLog(#"No response received");
}
}]resume];
You could try using a NSDictionary for the parameters. The following will send the parameters correctly to a JSON server.
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://thapi.xyz/auth/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *login = [[NSDictionary alloc] initWithObjectsAndKeys: #"username":#"exampleMail#gmail",#"password":#"123456",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:login options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
Hope this works Properly...:)
try also to correct "setValue:postLenght", since I guess that doesn't exist, and will probably set Content-Length to 0.

How to solve warning message: Sending 'viewController const __strong to parameter of incompatible type 'id<nsurlsessiondelegate>

The following code gave a warning of :
Sending 'viewController const __strong to parameter of incompatible
type 'id
Here is my code:
- (void)postRequestWithParam: (NSDictionary *)param onCompletion: (CompletionHandler)completionHandler
{
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.timeoutIntervalForRequest = 30.0;
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString: #"http://test.demo.net/demoapp/index.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
if(param == nil)
param = [NSDictionary dictionary];
NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if (!error)
{
completionHandler(YES, [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error], nil);
NSString *responseStr = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"res...%#",responseStr);
NSLog(#"RESPONSE: %#", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
}
else
{
completionHandler(NO, nil, error);
}
}];
[postDataTask resume];
}
Confirm <NSURLSessionDelegate> in your header file and it will solve the issue i think,
#interface ViewController : UIViewController <NSURLSessionDataDelegate>
It is because you are setting delegate to self in NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; So it's requires to confirm NSURLSessionDataDelegate protocol.

Objective c post request not sending the data

Good day.Im trying to send simple post data to server.This is the code how i do it.
-(void)makeRequest:(NSString*)stringParameters{
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://vaenterprises.webatu.com/Authentication.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/text" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/text" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString* postData = #"tag=hello&username=yo&something=something";
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[self parseJson:data];
}];
[postDataTask resume];
}
It looks great till i echo the whole post from php side like this
echo json_encode($_POST);
and i print the result in the iOS like this
-(void)parseJson:(NSData*) data{
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
NSDictionary* jsonObject= [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
NSLog(#"%#",myString);
}
this issue is that i get empty string..so it means that post data not being send and that is 10000 percent objective c side issue and i have no clue why its so as in this method we only got setHttpBody with the actual string which contains key and value separated by & but that data not being send as you can see.So what am i doing wrong?Please tell somebody
Http body has to be of type NSData. Try out following code
NSString* stringData = #"tag=hello&username=yo&something=something";
NSData* data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];

How to post data in url using json?

This is my code by which i am posting data in url.
- (IBAction)Register:(id)sender {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"]];
[request setHTTPMethod:#"POST"];
NSLog(#"the company name is:%#",_CompanyName.text);
NSLog(#"the email is:%#",_Email.text);
NSLog(#"the password is:%#",_Password.text);
NSLog(#"the password again is:%#",_Passwordagin.text);
NSString *strParameters =[NSString stringWithFormat:#"email_id=%#&company_name=%#&password=%#",_Email.text,_CompanyName.text,_Password.text, nil];
NSLog(#"the data Details is =%#", strParameters);
NSData *data1 = [strParameters dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data1];
// NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
//}];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"[http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
}];
[postDataTask resume];
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"[http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,
nil];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *bodyData = [NSJSONSerialization dataWithJSONObject:mapData options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPBody:bodyData];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponce = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:[strResponce dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"Result: %#",dictResponse);
Try the code in this gist I created
Which is generated using PAW .

Resources