How to pass parameter in php webservice? - iphone

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

Related

posting data to server from iphone app

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

error while making URL request iPhone

I asked a question and followed following way(suggested by Jaybit):
Pass username and password in URL for authentication
Now, I'm getting this error(stack track):
2013-02-12 11:56:11.734 Calendar[4074:c07] didReceiveData
2013-02-12 11:56:19.519 Calendar[4074:c07] receivedString:<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
at System.Xml.XmlReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
--- End of inner exception stack trace ---</soap:Text></soap:Reason><soap:Detail /> </soap:Fault></soap:Body></soap:Envelope>
(lldb)
Here is my code:
- (IBAction)btnLoginClick:(id)sender
{
//Call Calendar View
if(self.viewController == nil) {
CalendarViewController *detailView = [[CalendarViewController alloc] initWithNibName:#"CalendarViewController" bundle:nil];
self.viewController = detailView;
}
NSString *userName = [NSString stringWithFormat:#"parameterUser=%#",txtUserName];
NSString *passWord = [NSString stringWithFormat:#"parameterPass=%#",txtPassword];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://URL/service1.asmx?"]];
NSString *postString = [NSString stringWithFormat:#"username=%#&password=%#",userName, passWord];
NSLog(#"%#",userName);
NSLog(#"%#",passWord);
NSData *postData = [NSData dataWithBytes: [postString UTF8String] length: [postString length]];
//URL Requst Object
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:600];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: postData];
appConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[self.appConnection start];
//tryed with Async...
/* NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSString *receivedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}];*/
[self.navigationController pushViewController:self.viewController animated:YES];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
tempdata = 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:tempdata encoding:NSUTF8StringEncoding];
NSLog(#"receivedString:%#",receivedString);
}
please help.thank.
I've worked with requesting a soap URL before, the following code worked for me:
NSString *soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
"<soap:Body>\n"
"<YourServiceName xmlns=\"http://tempuri.org/\">\n"
"<username>%#</username>\n"
"<passowrd>%#</passowrd>\n"
"</YourServiceName>\n"
"</soap:Body>\n"
"</soap:Envelope>\n", userName, passWord
];
NSURL *url = [NSURL URLWithString:#"http://URL/service1.asmx"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: [NSString stringWithFormat:#"http://tempuri.org/%#",service] forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest setTimeoutInterval:10];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
responseData = [[NSMutableData data] retain];
}
else
{
NSLog(#"theConnection is NULL");
}

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

post json request in iphone

I have a mySQL database, an iPhone client and a RESTful Web Service(using jersey) as an intermediate layer between them. I connected successfully to the database and implemented a GET Request. I have problem to POST to it.
In this way I prepare JSON to transfer:
NSDate *date = self.pickerView.date;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
NSString *stringFromDate = [formatter stringFromDate:date];
[formatter release];
NSArray *keys = [NSArray arrayWithObjects:#"name", #"mail",#"password",#"mobil", #"birth", #"city" , nil];
NSArray *objects = [NSArray arrayWithObjects:name.text, mail.text, password.text, mobil.text, stringFromDate, city.text, nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
I tried two ways to POST, but non of them was successful.
1) using JSON NSString:
NSURL *url = [NSURL URLWithString:#"http://192.168.1.100:8080/rest/login/post"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString 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];
2) using NSData:
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.100:8080/rest/login/post"]];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[urlRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:jsonData];
NSURLConnection * myConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
I have this method also in my codes:
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSMutableData *d = [[NSMutableData data] retain];
[d appendData:data];
NSString *a = [[NSString alloc] initWithData:d encoding:NSASCIIStringEncoding];
NSLog(#"Data: %#", a);
}
I got this error in Console:
Data: <html><head><title>Apache Tomcat/7.0.23 - Error report</title><style><!--
H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-
size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-
color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-
serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-
family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-
family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-
family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color :
black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status
406 - Not Acceptable</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p>
<b>message</b> <u>Not Acceptable</u></p><p><b>description</b> <u>The resource identified by
this request is only capable of generating responses with characteristics not acceptable
according to the request "accept" headers (Not Acceptable).</u></p><HR size="1"
noshade="noshade"><h3>Apache Tomcat/7.0.23</h3></body></html>
I appreciate for any help.
The response says, that it doenst like this
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
So it doenst offer to respond with json.
The documentation of the web service should list all possible values.
You may want to try
[request setValue:#"application/xml" forHTTPHeaderField:#"Accept"];
Or reconfigure tomcat to accept json as response format.

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