posting data to server from iphone app - iphone

I am posting data to server from iphone app but it gives exception while reading post line code about "excess bad access".Same code I use for sending four variables data then it is working fine if i add more variables in post it gives an error.
NSString*category=titleCategory;
NSString*sub_Category=titleSubCategory;
NSString*content_Type=#"Audio";
content_Title=TitleTextField.text;
NSString*content_Title=content_Title;
NSString*publisher=#"Celeritas";
content_Description=descriptionTextField.text;
NSString*content_Description=content_Description;
NSString*content_ID=#"10";
NSString*content_Source=#"http://www.celeritas-solutions.com/pah_brd_v1/productivo/productivo/pro/ali.wav";
NSString *post =[[NSString alloc] initWithFormat:#"category=%#&sub_Category=%#&content_Type=%#&content_Title=%#&publisher=%#&content_Description=%#&content_ID=%#&content_Source=%#",category,sub_Category,content_Type,content_Title,publisher,content_Description,content_ID,content_Source];
NSURL *url=[NSURL URLWithString:#"http://www.celeritas-solutions.com/pah_brd_v1/productivo/addData.php"];
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);
Below is the line where it breaks the code
NSString *post =[[NSString alloc] initWithFormat:#"category=%#&sub_Category=%#&content_Type=%#&content_Title=%#&publisher=%#&content_Description=%#&content_ID=%#&content_Source=%#",category,sub_Category,content_Type,content_Title,publisher,content_Description,content_ID,content_Source];

Try this
NSString *args = #"category=%#&sub_Category=%#&content_Type=%#&content_Title=%#&publisher=%#&content_Description=%#&content_ID=%#&content_Source=%#";
NSString *values=[NSString stringWithFormat:args,category,sub_Category,content_Type,content_Title,publisher,content_Description,content_ID,content_Source];
NSData *postData = [values dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *path = [[NSString alloc] initWithFormat:#"%s",your urlpath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:path]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:[values dataUsingEncoding:NSISOLatin1StringEncoding]];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&err];
NSString *returnString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[NSURLConnection connectionWithRequest:request delegate:self];
//NSLog(#"String==> %#",returnString);
Hope this helps...
Good luck !!

Following code a help a lot while i test into the project as well as
In .h File
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController{
NSURLConnection *connection;
NSMutableData *responseData;
}
#end
In.m File
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString*category=#"Cat1";
NSString*sub_Category=#"Title";
NSString*content_Type=#"Audio";
NSString* content_Title=#"Test";
NSString*publisher=#"Celeritas";
NSString*content_Description=#"Content Description";
NSString*content_ID=#"10";
NSString*content_Source=#"http://www.celeritas-solutions.com/pah_brd_v1/productivo/productivo/pro/ali.wav";
NSString*post = [NSString stringWithFormat:#"category=%#&sub_Category=%#&content_Type=%#&content_Title=%#&publisher=%#&content_Description=%#&content_ID=%#&content_Source=%#",category,sub_Category,content_Type,content_Title,publisher,content_Description,content_ID,content_Source];
NSURL *url=[NSURL URLWithString:#"http://www.celeritas-solutions.com/pah_brd_v1/productivo/addData.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
connection=[NSURLConnection connectionWithRequest:request delegate:self];
if(connection){
responseData=[NSMutableData data];
}
}
#pragma NSUrlConnection Delegate Methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// [delegate APIResponseArrived:NULL];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString =[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// [delegate APIResponseArrived:responseString ];
NSLog(#"%#",responseString);
}
This code solve your problem.

I got the solution of the question actually there was variable assignment issue for their invailded address that is why it was giving access bad error i assigned values directly then it worked for me fine like
NSString*category=#"Category";
NSString*sub_Category=#"Working";
NSString*content_Type=#"Audio";
NSString*content_Title=#"Content Title";
NSString*publisher=#"Celeritas";
NSString*content_Description=#"ContentDescription";
NSString*content_ID=#"10";
NSString*content_Source=#"http://www.celeritas-solutions.com/pah_brd_v1/productivo/productivo/pro/ali.wav";
NSString *post =[[NSString alloc] init];
post = [NSString stringWithFormat:#"category=%#&sub_Category=%#&content_Type=%#&content_Title=%#&publisher=%#&content_Description=%#&content_ID=%#&content_Source=%#",category,sub_Category,content_Type,content_Title,publisher,content_Description,content_ID,content_Source];
NSURL *url=[NSURL URLWithString:#"http://www.celeritas-solutions.com/pah_brd_v1/productivo/addData.php"];
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];

Related

Leak with HttpRequest Method - Objective-c

I was Analyze my app for searching any leak, and here we are with a "Potential leak of an object stored into replyString".
I tried every release than I could, but nothing change, so I'm here asking for some help.
I make this method in my WebService Class.
-(NSString *)httpRequest{
NSData *postData = [self dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:adresse]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *replyString = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding: NSASCIIStringEncoding];
return replyString;
}
Thanks :)
You are creating the replyString with alloc init which means replyString needs to be released, therefore:
return [replyString autorelease];

How to pass parameter in php webservice?

I am working in an app in which i need to pass the json object in that parameter of the request string, now I am stuck here and have no idea how to do this.
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [NSMutableData data] ;
NSString *service = #"http://localhost.abc.com/index.php?p=api/user/register";
NSString *requestString = [NSString stringWithFormat:#"{\"Name\":\"%#\",\"Email\":\"%#\",\"Password\":\"%#\",\"PasswordMatch\":\"%#\",\"TermsOfUSe\":\"1\"}",txtusername.text,txtemail.text,txtpassword.text,txtretypepassword.text];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *urlLoc=#"";
urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL:- %#",urlLoc);
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];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSLog(#"%#",request);
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [NSMutableData data] ;
NSString *service = #"http://localhost.abc.com/index.php?p=api/user/register";
NSString *requestString = [NSString stringWithFormat:#"{\"Name\":\"%#\",\"Email\":\"%#\",\"Password\":\"%#\",\"PasswordMatch\":\"%#\",\"TermsOfUSe\":\"1\"}",txtusername.text,txtemail.text,txtpassword.text,txtretypepassword.text];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *urlLoc=#"";
urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL:- %#",urlLoc);
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];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSLog(#"%#",request);
Delegate method of Connection
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
//**check here for responseData & also data**
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:#"Connection failed: %#", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
//do something with the json that comes back ... (the fun part)
}
/ /// / ///////// EDITED Answer /////////////////////
GET Method: In this method you can append the request data behind the web- service.As you doing now by line [request setHTTPMethod: #"POST"];.
POST Method: In this method, you can't append the requested data. But pass the dictionary as a parameter. Like below:
NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:#"StoreNickName"],
[[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:#"user_question"], nil];
NSArray *keys = [NSArray arrayWithObjects:#"nick_name", #"UDID", #"user_question", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:#"question"];
NSString *jsonRequest = [jsonDict JSONRepresentation];
NSLog(#"jsonRequest is %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"https://xxxxxxx.com/questions"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

Pass username and password in URL for authentication

I want ot pass username and password in URL(web service) for user authentication which will return true and false.I'm doing this as following:
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSData *getUserData = [userName dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getUserLength = [NSString stringWithFormat:#"%d",[getUserData length]];
NSData *getPassData = [passWord dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getPassLength = [NSString stringWithFormat:#"%d",[getPassData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://URL/service1.asmx"]];
[request setHTTPMethod:#"GET"];
Now, I wanted to know How can I pass my username and password in this URL to make request.
Could any one please suggest or give some sample code?
Thanks.
Try this :-
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName.text];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword.text];
NSData *getUserData = [userName dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getUserLength = [NSString stringWithFormat:#"%d",[getUserData length]];
NSData *getPassData = [passWord dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getPassLength = [NSString stringWithFormat:#"%d",[getPassData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?%#&%#",userName,passWord]]];
[request setHTTPMethod:#"GET"];
Hope it helps you..
NSString *urlStr = [NSString stringWithFormat:#"http://URL/service1.asmx?%#&%#",userName,passWord];
[request setURL:[NSURL URLWithString:urlStr]];
To improve the secure , you may use the Http Basic Authentication.
There are answer here.
First off I would not pass a username and password across in a url. You should do this using post.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?"]];
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSString *postString = [NSString stringWithFormat:#"username=%#&password=%#",userName, passWord];
NSData *postData = [NSData dataWithBytes: [postString UTF8String] length: [postString length]];
//URL Requst Object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:TIMEOUT];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: postData];
This is more secure then passing sensitive data across in a url.
Edit
To get the response you can check this out. NSURLConnection and AppleDoc NSURLConnection
You can use a few different methods to handle the response from the server.
You can use NSURLConnectionDelegate
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.connection start];
along with the delegate call backs:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"didReceiveData");
if (!self.receivedData){
self.receivedData = [NSMutableData data];
}
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}
Or you can also use NSURLConnection sendAsynchronousRequest block
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}];

Posting data from iphone app to server

I am sending data from iphone application to server but when it reads post String it crashes in the application and do not move forward
-(void)submitSurveyAnswers{
NSString*survey_question_response_id="1";
NSString*survey_id=#"1";
NSString *question_id =#"1";
NSString *survey_response_answer_id =#"1";
NSString *post =[[NSString alloc] initWithFormat:#"survey_question_response_id=%#&survey_id=%#&question_id=%#&survey_response_answer_id=%#",survey_question_response_id,survey_id,question_id,survey_response_answer_id];
NSLog(post);
NSURL *url=[NSURL URLWithString:#"http://myserver-solutions.com/app/surveyAnswer.php?"];
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);
}
You have created one string with below way:
NSString*survey_question_response_id="1"; //Missing '#' while initializing string
It should be created like below way:
NSString*survey_question_response_id=#"1"; //Added '#' while initializing string
NSString*survey_question_response_id="1";
is wrong. Strings between plain double quotes are C string (0-terminated character pointers), and aren't valid NSString instances. I'm sure you wanted to 1. learn to use a debugger 2. write
NSString *survey_question_response_id = #"1";
instead.

NSURLRequest: How to change httpMethod "GET" to "POST"

GET Method, it works fine.
url: http://myurl.com/test.html?query=id=123&name=kkk
I do not have concepts of POST method. Please help me.
How can I chagne GET method to POST method?
url: http://testurl.com/test.html
[urlRequest setHTTPMethod:#"POST"];
try this
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",username.text,password.text];
NSLog(#"%#",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#" server link here"]]];
[request setHTTPMethod:#"POST"];
NSString *json = #"{}";
NSMutableData *body = [[NSMutableData alloc] init];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300)
{
NSLog(#"Response: %#", result);
}
// create mutable request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// set GET or POST method
[request setHTTPMethod:#"POST"];
// adding keys with values
NSString *post = #"query=id=123&name=kkk";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request addValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];