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];
Related
I have made one demo code for print the data from the web Services,
Code
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://54.149.46.64/API/video.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"video" forHTTPHeaderField:#"list"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
}] resume];
Output
JSON_Webservices[4496:150468] requestReply: {"Status":"Fail","Message":"Please enter required fields"}
Why i am not able to fetch data from the WS? Please help me.
Working Fine In Postman
Image
Thank You.
header
Please check this...
NSURL *aUrl = [NSURL URLWithString:#"XXXX"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *postString = #"list=video";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
NSError *jsonError;
NSData *objectData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"requestReply: %#", json);
}] resume];
i am working on Google cloud endpoint with datastore. When i am passing data through Android & iOS with method POST , it is getting saved in datastore with empty record. i.e. request is properly working but the way i am sending data is wrong. please help me for this.
For iOS, code is mentioned below :
NSDictionary *headers = #{ #"content-type": #"application/json",
#"cache-control": #"no-cache",
#"postman-token": #"404012ff-722e-c5d8-48db-fa7fb3260841"};
NSLog(#"header %#",headers);
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"enter url here..."]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSString* strRequest=#"";
strRequest =[[NSString alloc] initWithFormat:#"displayEmail=%#&displayName=%#",#"sonal#gmail.com",#"sonal"];
NSLog(#"url is %# parameter = %#", request , strRequest);
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [strRequest dataUsingEncoding:NSUTF8StringEncoding]];
[request setAllHTTPHeaderFields:headers];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *responseBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"responce Body===>%#",responseBody);
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"responce%#", httpResponse);
}
}];
[dataTask resume];
You need to set the httpBody property of your request. If you don't provide a body for the POST, of course it's blank.
https://developer.apple.com/reference/foundation/nsmutableurlrequest/1409064-httpbody
Or Objective-C
https://developer.apple.com/reference/foundation/nsmutableurlrequest/1409064-httpbody?language=objc
We got a solution..
we changed the way of passing data..
here is code :
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:syncURL]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
NSData *requestData = [NSData dataWithBytes:[serverSyncAPIRequestJSON UTF8String] length:[serverSyncAPIRequestJSON length]];[request setHTTPMethod:#"POST"]; [request setHTTPBody:requestData]; [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
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)
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];
I'm attempting to communicate with a backend using NSURLSession, however, the backend wasn't set up to properly read NSData, so it views the NSData login details I send over as false, I wanna know if its possible to get NSURLSession to send raw strings rather than NSData objects. I've looked in books and the webs and I've been stumped for weeks.
Redoing the backend is not an option, the engineer in charge of that left. Any help is welcome.
Thanks. Here's what I've done so far, in case anyone needs to see some code.
NSError *error;
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration ];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
NSString *rawUrlString = #"backend_url";
NSURL *url = [NSURL URLWithString:rawUrlString];
NSLog(#"%#", url);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
login data here
nil];
//NSLog(#"%#", parameters);
NSData *rawJson = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
NSString *myString = [[NSString alloc] initWithData:rawJson encoding:NSUTF8StringEncoding];
NSData *finalData = [myString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *body = [NSMutableData data];
[body appendData:finalData];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:body];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"charset"];
[request setValue:#"XMLHttpRequest" forHTTPHeaderField:#"X-Requested-With"];
NSURLSessionDataTask *postTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(#"%#", [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]);
}];
[postTask resume];
`
UPDATE: I've cleaned up the unnecessary bits this is the final code (still doesn't work though)
NSError *error;
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration ];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
NSString *rawUrlString = #"backend_url";
NSURL *url = [NSURL URLWithString:rawUrlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:login details nil];
NSData *rawJson = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:rawJson];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSURLSessionDataTask *postTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSLog(#"%#", [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]);
}];
[postTask resume];
Your backend is setup to handle NSData. It's impossible to send a string over an internet connection, you can only send NSData and all servers expect it.
This code here is wrong:
NSData *rawJson = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
NSString *myString = [[NSString alloc] initWithData:rawJson encoding:NSUTF8StringEncoding];
NSData *finalData = [myString dataUsingEncoding:NSUTF8StringEncoding];
Instead just do this:
NSData *finalData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&error];
The NSData object will contain a string in the correct format for the server to also recognise as a string. Note it will be in UTF-8 encoding, perhaps on some servers you will want to change that to something else.