Store the data in web server using HTTP Post methd - ios

I tried with below code. Here the problem is parameters are directly passing to the database from url.But i need to send the data from Text fields.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:#"http:UserProfile.svc/InsertUserDetailsNew?Name=RajeevLeader&FirstName=rajeev&DateofBirth=2012-02-03&Sex=M&Country=India&City=Banglore&PhoneNumber=8523898947&IncumbentonPremimum=true"]];
NSLog(#"url is %#",request);
NSString *requestString =[NSString stringWithFormat:#"Name=%#&FirstName=%#&DateofBirth=%#&Sex=%#&Country=%#&City=%#&PhoneNumber%#&IncumbentonPremimum=%#",name.text, firstname.text,dob.text,gender.text,country.text,city.text,phone.text,premiumtextfield.text];
NSLog(#" RequestString: %#",requestString);
NSMutableData *requestData =[NSMutableData dataWithBytes:[requestString UTF8String] length: [requestString length]];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (con)
{
NSLog(#"data sent ");
} else
{
NSLog(#"Not sent");
}
[con start];

just change your URL for the following method
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:#"http://192.168.2.4:98/UserProfile.svc/InsertUserDetailsNew"]];
NSString *requestString = [[NSString alloc]
initWithFormat:#"{ \"Name\" : \"%#\" , \"FirstName\" : \"%#\" , \"DateofBirth\" : \"%#\" , \"Sex\" : \"%#\", \"Country\" : \"%#\", \"City\" : \"%#\", \"PhoneNumber\" : \"%#\" , \"FirstName\" : \"%#\"}",
name.text, firstname.text,dob.text,gender.text,country.text,city.text,phone.text,premiumtextfield.text];
NSLog(#" RequestString: %#",requestString);
NSMutableData *requestData =[NSMutableData dataWithBytes:[requestString UTF8String] length: [requestString length]];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[con start];

you have to pass parameters afterwords & not with the url.

Related

How to make json post request?

I have to make json post request with the following request parameters,
{
"method":"login",
"data":{
"username":"korea",
"password":"123456"
}
}
I use the following code to make the request,
NSString *jsonRequest = [NSString stringWithFormat:#"{""\"\method:\"\login\"\"\,""\data:\"{\"\"username\":\"%#\",\"password\":\"%#\"}",username,password];
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http://myurl..."];
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/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
I have to get the response but Im not be able to get the response
Try this
NSDictionary *objectDic = #{#"username" : username, #"password" : password};
NSDictionary *dataDic = #{#"data" : objectDic};
NSDictionary *methodDic = #{#"method" : #"login", #"data": dataDic};
NSData *requestData = [NSJSONSerialization dataWithJSONObject:methodDic
options:NSJSONWritingPrettyPrinted
error:nil];
[request setHTTPBody: requestData];

NSURLConnection post request stops posting after some time

I am trying to post some values to my web service which is working for android version nicely and for iOS it works for about 12 requests then it stops sending. What am i doing wrong?
I am sending about 1 per second.
-(void) PostDataToServer:(NSMutableArray*) value
{
NSString *xValue = [NSString stringWithFormat:#"%#", [value objectAtIndex:0]];
NSString *yValue = [NSString stringWithFormat:#"%#", [value objectAtIndex:1]];
NSString *jsonRequest = [NSString stringWithFormat:#"{\"person\":\"%#\",\"x\":\"%#\",\"y\":\"%#\",\"z\":\"%#\"}",#"1",xValue ,yValue ,#"0.0"];
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"mywebserviceURL"];
request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSData *urlData= connection= [NSURLConnection connectionWithRequest:request delegate:self];
NSLog(urlData);

Miss parameter in http post

NSString * aToken = [[[NSUserDefaults standardUserDefaults] arrayForKey:#"accessToken"] firstObject];
NSString * post = [NSString stringWithFormat:#"code=%#", #"035571"];
NSData * postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString * postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"url"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[request setValue:#"no-cache" forHTTPHeaderField:#"Cache-Control"];
[request setValue:[NSString stringWithFormat:#"Bearer %#", aToken] forHTTPHeaderField:#"Authorization"];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[conn start];
the error is: {"error":"invalid_request","error_description":"Required field is missing. 'code'"}
how to fix it? any idea?

NSURLConnection with POST doesn't work

I'm trying request a URL parsing parameters with POST, but mypage.php is not receiving this parameters...
Here is my code:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://myurl/mypage.php"]];
NSString *params = [[NSString alloc]initWithFormat:#"name=%#&surname=%#&location=%#&email=%#&password=%#&gender=%#&tipo=%#", name, surname, location, email, password, gender, tipo];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(params);
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
webData = [[NSMutableData data] retain];
}
else
{
}
and mypage.php
if($_POST['name'] != "" && $_POST['email'] != "")
//Here the $_POST['name'] and the $_POST['email'] are empty...
You're not starting the connection. You should do it with a [conn start];
Try this:
NSString *params=[NSString stringWithFormat:#"name=%#&surname=%#&location=%#&email=%#&password=%#&gender=%#&tipo=%#", name, surname, location, email, password, gender, tipo];
NSData *postData=[params dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"http://myurl/mypage.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[request setValue:[NSString stringWithFormat:#"%i",postData.length] forHTTPHeaderField:#"Content-Length"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (data!=nil) {
NSString *output=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"output: %#", output);
}else{
NSLog(#"data is empty");
}

send JSON Object Request to Server

Iam sending JSON Object request to the server but server returns Status Code 405. how to solve this problem. please any one help me.
My code :
+(NSData *)GpBySalesDetailed:(NSMutableDictionary *)spDetailedDict{
NSLog(#"spDetailedDict:%#",spDetailedDict);
NSString *dataString = [spDetailedDict JSONRepresentation];
NSLog(#"%#dataString",dataString);
return [dataString dataUsingEncoding:NSUTF8StringEncoding];
}
-(void)requestWithUrl:(NSURL *)url WithJsonData:(NSData *)JsonData
{
NSMutableURLRequest *urlRequest=[[NSMutableURLRequest alloc]initWithURL:#"http://srbisolutions.com/SmartReportService.svc/GpBySalesPersonDetailed];
if (JsonData != nil) {
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:JsonData];
}
else
{
[urlRequest setHTTPMethod:#"GET"];
}
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
[conn start];
}
HTTP Code 405 means "Method not allowed", it does not accept a post request for this particular URI. Either the server must be configured to accept POST requests or it should offer another URI.
try this
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:YOURURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0 ];
NSLog(#"final request is %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//Here postData is a Dictionary with key values in web services format use ur own dic
[request setHTTPBody:[[self convertToJSON:postData] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *contentLength = [NSString stringWithFormat:#"%d",[[request HTTPBody] length]];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
self.responseData = [NSMutableData data];
}
//============JSON CONVERSION========
-(NSString *)convertToJSON:(id)requestParameters
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestParameters options:NSJSONWritingPrettyPrinted error:nil];
NSLog(#"JSON DATA LENGTH = %d", [jsonData length]);
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON STR LENGTH = %d", [jsonString length]);
return jsonString;
}
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"yourURL"]];
[theRequest setHTTPMethod:#"POST"];
NSDictionary *jsonRequest =
[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#//add your objects
]
forKeys:[NSArray arrayWithObjects:
title,
link,
nil]];
NString *jsonBody = [jsonRequest JSONRepresentation];
NSLog(#"The request is %#",jsonBody);
NSData *bodyData = [jsonBody dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:bodyData];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// create the connection with the request
// and start loading the data
theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

Resources