how to write data on server? - iphone

i am making a registration page were user can register?
this is my code..............
-(IBAction)btn_log:(id)sender
{
//NSString* username = nameInput.text;
//NSString* pass = passInput.text;
NSString* firstname = nameInput.text;
NSString* lastname = passInput.text;
NSString* bname = lastInput.text;
NSString *post =
[[NSString alloc] initWithFormat:#"fname=%#&lname=%#&email=%#",firstname,lastname,bname];
//NSString *post = [[NSString alloc]initWithFormat:#"fname=firstname&lname=lastname&email=bname];
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
NSString * postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest * request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.yoursite.com/file.php"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) NSLog(#"Connection Successful");
}
But it's not working so please can anyone suggest me where i am making mistake.

try in this way may be it will help you
Nsurl *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.yoursite.com/file.php"]]];
nsstring *body = [nsstring stringwithformat:#"%#,%#",nameinput,paasinput];
nsmutableurlrequest *request = [nsmutablerequest alloc]initwithurl:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request sethttpbody:[body dataysubgebcidubg:asciiiencoding allowlossyconversion : true]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) NSLog(#"Connection Successful");

NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
Replace above line of your code with following line. Probably it will work.
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

Related

I am sending dictionary in json and its have two array and multiple value but i am getting response access denied

I am sending two array and multiple value throw json but when i send this i am getting success code 200 and its response showing access denied pls any one give me right way to solve it **
-(void)SaveColumnConnection
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURLURLWithString:#"http://xxxyyyzzzz.php"]];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:oneRowColumn,#"oneRowCols",memberTid,#"table_title_id",totalRowStr,#"totRow",rowandColumn,#"tempColName",tableOptIdArray ,#"tempOptid",companyId,#"companyid",#"savecolumniphone",#"tag",nil];
NSLog(#"dict %#",dict);
SBJSON *parser =[[SBJSON alloc] init];
NSString *jsonString = [parser stringWithObject:dict];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSHTTPURLResponse *HTTPResponse = (NSHTTPURLResponse *)response;
NSInteger statusCode = [HTTPResponse statusCode];
if (statusCode==200) {
//Request goes in success
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Json for post array ----------%#",str);
}
else{
///request is get failed
NSLog(#"Error Description %#",[error localizedDescription]);
}
}];
[request release];
}
Wanted to see your php code as well..Anyways please check whether the following example helps you out... Here I am not sending any dictionary values, adjust the code to your requirement :)
NSString *jsonRequest = #"{\"username\":\"user\",\"password\":\"pwd\"}";
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http://xxxyyyzzzz.php"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
try this code
NSDictionary *dict = [NSDictionary
dictionaryWithObjectsAndKeys:oneRowColumn,#"oneRowCols",memberTid,#"table_title_id",totalRowStr,#"totRow",rowandColumn,#"tempColName",tableOptIdArray ,#"tempOptid",companyId,#"companyid",#"savecolumniphone",#"tag",nil];
NSString *jsonRequest = [dict JSONRepresentation];
NSURL *url = [NSURL URLWithString:#"http://xxxyyyzzzz.php"];
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];
connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];

i want to send request by POST on iPhone,but the body can't be received by server [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
iPhone SDK Xcode 4.2 iOS 5- How do i send a json to url ? (POST not GET) [Resolved]
NSDictionary *requestDic=[NSDictionary dictionaryWithObjects:values forKeys:keys];
NSString *jsonreq=[requestDic JSONRepresentation];
NSURL *requrl=[NSURL URLWithString:[NSString stringWithFormat:#"%#index.php?r=%#&te=%#&noCheck=1&checkInstall=start",[Info serverUrl],[dictParameters objectForKey:#"r"],[dictParameters objectForKey:#"te"]]];
requrl = [NSURL URLWithString:[[requrl absoluteString] stringByAppendingString:subUrl]];
NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:requrl];
[req setHTTPMethod:#"POST"];
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:#"application/json-x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSData *requestData=[NSData dataWithBytes:[jsonreq UTF8String] length:[jsonreq length]];
[req setHTTPBody:requestData];
[browser loadRequest:req]
Dilshand's answer is ok , but you can use ASIFormDataRequest for ease. like follow
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:mobileApplicationId forKey:#"mobileApplicationId"];
[request setPostValue:mobileApplicationVersion forKey:#"mobileApplicationVersion"];
[request setPostValue:userID forKey:#"userId"];
[request setPostValue:pass forKey:#"password"];
[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request startAsynchronous];
What you want to post server give complete detail and what error you are getting
try following i have done using this to send data to server and it works fine for me hope this helps
NSString *post =[[NSString alloc] initWithFormat:#"ProviderNPI=%#&PatientID=%#&FileURL=%#&FileTYPE=%#&DataSynID=%#& AppointmentListingsID=%#",providerNPI,patientID,FILEURL,FILETYPE,dataSynID,appointmentListingID];
NSURL *url=[NSURL URLWithString:#"http://myserver.com/Sync.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);
NSURL *url = [NSURL URLWithString:#"http://www.invoicera.com/app/api/check_json_api.php?token=7B92C122473A3D6F54E60D20AC5526D0"];
NSString *jsonRequest = [NSString stringWithFormat:#"&json_data=%#",[[NSString stringWithFormat:#"{\"listInvoice\":{\"client_id\":\"\",\"date_from\":\"\",\"date_to\":\"\",\"invoice_number\":\"\",\"invoice_record_status\":\"\",\"invoice_status\":\"\",\"page\":\"1\",\"per_page_record\":\"20\"}}"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",jsonRequest);
NSData *json_data = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
NSLog(#"%#",json_data);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: json_data];
NSLog(#"%#",json_data);
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [json_data length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:[[jsonRequest stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
dataUsingEncoding:NSUTF8StringEncoding
allowLossyConversion:YES]];
// [NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
NSURLConnection *nsUrlConnection=[[NSURLConnection alloc]
initWithRequest:request
delegate:self];
// Successful connection.
if (nsUrlConnection) {
// [self initSpinner];
// [self spinBegin];
NSMutableData *data = [[NSMutableData alloc] init];
self.receivedData=data;
[data release];
}
// Unsuccessful connection.
else {
}
// Clean up
[url release];
[request release];
// Close keypad.

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];

XML parsing is not working as expected in Objective-C

I am new to iPhone programming, and this is the first time parsing XML file. I have added the url and also hardcoded the XML file into the string, however I am not getting the correct response from the server.
Here is my code:
NSString *post = #"<?xml version=\"1.0\"encoding=\"UTF-8\"?<request><call>GetNewChapters</call><udid>1000000000000000000000000000000000000000</udid><book_id>1</book_id><updatetoken>B20100125054802</updatetoken></request>";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url=[NSURL URLWithString:#"https://www.paisible.com/babelle_api"];
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];
NSString *myStr = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"String Value :%#",myStr);
NSLog(#"theRequest: %#", request);
NSURL *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}
Where as webdata is NSMutable data. Please let me know what errors I have made in my parsing code.
Try to replace
NSURL *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
with the following:
NSURLResponse *resp;
NSError *error;
NSMutableData *webData = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&error];
Than, check what "webData" contains.

How to append querystring in url using objective c?

NSString *post = #"&username=adam&password=test";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://ws.myurl.com/svc-public/iPhoneAuthenticate.aspx?uname=adam&pword=test"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *response = [[NSString alloc] initWithData:returnData encoding:NSASCIIStringEncoding];
NSLog(response);
This is my url http://ws.myurl.com/svc-public/iPhoneAuthenticate.aspx, now I need to append the username and password dynamically.
How to append querystring in url? Please help me.
You can do it this way:
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://ws.myurl.com/svc-public/iPhoneAuthenticate.aspx?uname=%#&pword=%#",name, password]]];