Can't POST a request to service - objective-c

For some reason I always get Endpoint not found., but when I put it in the browser it works perfectly. I'm sure doing something wrong..
- (void)requestLoad:(NSString *)req_udid Age:(NSString *)req_age Gender:(NSString *)req_gender CheckBoxes:(NSString *)req_checkBoxes
{
NSString *post = [NSString stringWithFormat:#"/UpdatePersonalInterests/%#/%#/%#/%#/0",req_udid, req_age, req_gender, req_checkBoxes];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
//set up the request to the website
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:NSLocalizedStringFromTable(#"kServiceURL", #"urls", nil)]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",result);
}
Thanks!

It looks like you are using a Custom Service scheme. Did you register it in Target -> info - URLS Types? See the Apple Docs or Registering custom URL Schemes: Implementing Custom URL Schemes

So I've managed to do this with NSURLConnection and asynchronous request with this code:
- (void)getIntrests
{
NSString *req_udid = [PROUtils createOrLoadUserIdentifier];
NSString *webaddress = [kServiceBaseURL stringByAppendingString:[NSString stringWithFormat:#"/GetPersonalInterestsForUdid/%#",req_udid]];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:webaddress] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:
^(NSURLResponse* response, NSData* data, NSError* error) {
NSString* dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:kGotMediaFromServer object:dataString];
NSLog(#"Update response completed: %# with data: %# error: %#",response,dataString,error);
}];
}
Hope that it will be useful for someone.

Related

iMessage bubble calling web service freze the view

i am using iMessage bubble to create chat view working fine
https://github.com/kerrygrover/iMessageBubble
When i call my web service in my inside method this at end
- (IBAction)sendMessage:(id)sender
here is my web method calling function which gives result out put success and send my chat to the server, but my view freeze.
NSError *errorReturned = nil;
NSString *urlString = #"https://url/methodname”;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:employeeId forKey:#"employeeId"];
[dict setObject:employeename forKey:#"employeename"];
NSLog(#"dic=%#",dict);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&errorReturned];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", responseString);
//...do something with the returned value
}
}
plz create a new queue not run this code on main queue . you are running the code on main queue plz use this
dispatch_queue_t myQueue = dispatch_queue_create("myQueue", NULL);
// execute a task on that queue asynchronously
dispatch_async(myQueue, ^{
NSError *errorReturned = nil;
NSString *urlString = #"https://url/methodname”;
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:employeeId forKey:#"employeeId"];
[dict setObject:employeename forKey:#"employeename"];
NSLog(#"dic=%#",dict);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&errorReturned];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: jsonData];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", responseString);
//...do something with the returned value
}
});

How to send json data in the Http request to POST Method in JSON Parsing

I need to Parse below string to POST method in iOS
"jsonData":{"empId":"cxvd","password":"sfsd"}
But I m getting the error as
Res: Tomcat Error
HTTP Status 400 - Required String parameter 'jsonData' is not present
//------ Method I have used to Parse is ---------- //
+(void) requestToServerForLogin:(NSString*)userName andPassward: (NSString*)password onCompletion:(RequestCompletionHandler) handler
{
NSString *url = [Ip stringByAppendingString:#"login"];
NSString *jsonString = [NSString stringWithFormat:#"\"jsonData\":{\"empId\":\"%#\",\"password\":\"%#\"}",
userName,
password ];
NSURL *nsurl = [NSURL URLWithString:url];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:nsurl];
[urlRequest setTimeoutInterval:60.0f];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/json"
forHTTPHeaderField:#"Content-type"];
NSString *body = jsonString1;
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"urlRequest :%#",[body dataUsingEncoding:NSUTF8StringEncoding]);
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response,
NSData *data1, NSError *error)
{
NSString *res = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
if(handler) handler(res,error);
}];
}
Thanks in advance
There is way to much code. The substringToIndex and substringFromIndex are wrong, should not be in the code.
Use the literal syntax for the dictionaries:
NSDictionary *jsonDict = #{#"jsonData":#{#"password":password, #"empId":userName}};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:&error];

sending files to server and receiving feedback

I have this code who send a file to my server:
NSData *data = [NSData dataWithContentsOfFile:path];
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:#"name=thefile&&filename=recording"];
[urlString appendFormat:#"%#", data];
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *baseurl = #"http://websitetester.com/here.php";
NSURL *url = [NSURL URLWithString:baseurl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod: #"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];
NSLog(#"File Send to server!");
this code works perfectly but I would like to receive a return from the server, the php file at the end of the code I show:
<?php
if(...){
...
echo "Data Received";
}else{
...
echo "Error in server";
}
?>
All I'm trying is receive this echo in php and show an alert inside my app, how code I can implement inside my code to do that?
EDIT
Hey I find a code who receive the return data in objetive-c, the code is:
NSURLResponse* response;
NSError* error;
NSData* result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSString *returnString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(#"return: %#",returnString);
and now the code works the way I expected.

iOS http post response to NSDictionary or NSArray

I'm making a HTTP Post and I would like to know how to convert the response to NSDictionary, or NSArray. Here's my code:
NSString *post = [NSString stringWithFormat: #"SomeData=text", text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"https://www.my.site/receiver"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
EDIT:
The response looks like this after converting like this:
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
2011-12-04 11:50:00.924 Dancing Ruby[404:207] response: SID=DQAAAMAAAAAjy9MXrxh7Hi4nXTpyVTnqMR4c_W2wCQmLmO7xDHz7v91kl16tH-0UyazONU2nGjsUYxGzAPd9lvNcCGLfcz7YFLQRhG8yW8_wn3V46g8SY0A5bnfmGhuIbAMoCetow09cOnE7aYUzEZ4u5zVnJFoNepa9BlheFAA8JFLomw3luHedLkJZi_CQJO48CtwLZeIF9zhD5RNUDUretNh_1QBN2fHntSiqASMHHHyd9dtlTaXpokx_KIJovxo0dNYUJbs
LSID=DQAAAMIAAACgjuwUzSRNh2xXrWsdA81_fLVCguvatiHHU6b1dMm0TD6-lQyl-odfIfLGWgee4_j3HXUNsqtTm-aEFgylW2QURA5F9_1Fx8WRECIWOkUoLfWBGchoxRfhxKqCoD-zzgg1opjSmrDyv0U1NZRN7YGiqkLj4Fz_Qm6oPapov2_J33KT0ENFTKnqyzS0zU3wHgKSGb1aoKKO0ZJCTFk20AX3cLYPuMWoJcnyrLipCzZjkjwGEEhfgz31ISPS9OGezPzYJji-UxTmaJB7Va7SGquX
Auth=DQAAAMEAAACgjuwUzSRNh2xXrWsdA81_fLVCguvatiHHU6b1dMm0TD6-lQyl-odfIfLGWgee4_gex6ZHpCOn0tXFwuivD7ESwhFMJGdLRYSspk-leGqj-eCkXUgsg4DBvxPbdpREFlU_j0RGm_qufXlaScZV3x17plY5-xrhvhziEVFf3eLiHEmN9HHNwh8uElyYyJ1rLNAbIunpG3D10ASr4WPQDIz_52OOKy07CmQrBNDdUcpkT5bXqBe3Cdw8aqld0LZH2AIMEdj7PupfRaneJgF-nCBZ
You need to use some kind of parser for that. If the response is in XML you could use NSXMLParser. Here you can find a tutorial on how to use it. The same concept applies for any other kind of data. You have to know beforehand what to expect so you can parse it properly.
I hope it helps

connection failed : Bad Url (null) error while sending POST data from Xcode to classic ASP page.

In my iphone project, I need to pass member Id and pwd to a web server. I have tried my code with Synchronous as well as asynchronous request but I always get error : connection failed: Bad URL (null). can any one please help me to find what's wrong with the code?
My code:
NSString *post =[NSString stringWithFormat:#"memberId=%#&pwd=%#",txtUName.text,txtPwd.text];
NSLog(#"%#",post);
NSURL *url = [NSURL
URLWithString:#"http://testweb.talkfusion.com/videocenter/xlogin.asp%#"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
//set up the request to the website
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[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);
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
The %# at the end in your url is wrong. POST-data are not part of the url.