iPhone sending POST with NSURLConnection - iphone

I'm having some problems with sending POST data to a PHP script with NSURLConnection. This is my code:
const char *bytes = [[NSString stringWithFormat:#"<?xml version=\"1.0\"?>\n<mydata>%#</mydata>", data] UTF8String];
NSURL *url = [NSURL URLWithString:#"http://myurl.com/script.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
And my script.php is as simple as this:
<?php
echo $_POST['mydata'];
?>
This have worked for me in the past, but for some reason the output I get from NSLog(#"responseData: %#", responseData); now is just "<>" instead of "theData".
Probably some lame mistake somewhere but I can't seem to find it? Any ideas?

Your data is wrong. If you expect the data to be found in the $_POST array of PHP, it should look like this:
const char *bytes = "mydata=Hello%20World";
If you want to send XML Data, you need to set a different HTTP Content Type. E.g. you might set
application/xml; charset=utf-8
If you set no HTTP Content Type, the default type
application/x-www-form-urlencoded
will be used. And this type expects the POST data to have the same format as it would have in a GET request.
However, if you set a different HTTP Content Type, like application/xml, then this data is not added to the $_POST array in PHP. You will have to read the raw from the input stream.
Try this:
NSString * str = [NSString stringWithFormat:#"<?xml version=\"1.0\"?>\n<mydata>%#</mydata>", data];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[str dataUsingEncoding:NSUTF8StringEncoding]];
and on the server try the following PHP:
$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
$http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);
Please note that this only works if the HTTP header of your POST is not application/x-www-form-urlencoded. If it is application/x-www-form-urlencoded then PHP itself reads all the post data, decodes it (splitting it into key/value pairs), and finally adds it to the $_POST array.

Ah yeah... cheers. But the responseData output is like "<48656c6c 6f326f72 6c64>", don't you print NSData with %#? – per_pilot Jan 15 '10 at 13:57
that is because you are showing the "bytes" values you should pass it to NSString to see the real message
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"responseData: %#", string);

NSString *post =[NSString stringWithFormat:#"usertype(%#),loginname(%#),password(%#)",txtuser.text,txtusername.text,txtpassword.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:#"http://www.dacinci.com/app/tes2/login_verify.php"]];
[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 *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

POST data and XML data are not the same. You can send XML data just as you did, but the PHP code must parse the XML from the request body. PHP's xml_parse (http://php.net/manual/en/function.xml-parse.php) can help you do this.
Alternatively, if you would prefer sending POST data, set the request body like this:
const char *bytes = [[NSString stringWithFormat:#"mydata=%#", data] UTF8String];

If you use NSURLSession then in iOS9 set
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
request.HTTPMethod = #"POST";
In PHP set
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to SQL.";
//select a database to work with
$selected = mysql_select_db($db,$dbhandle)
or die("Could not select anons db");
echo "Connected to DB sucess.";
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET 'utf8'");
mysql_query("SET SESSION collation_connection = 'utf8_general_ci'");
In the db (MySql5) set utf-8_generic.

Related

Passing Spanish Language Data through JSON

I am fetching location data from foursquare api and then passing this data to webservice to insert in the database.
Now e.g. when i get location data for Mexico city then there are some special characters in it which gives following error:-
Unrecognized escape sequence. (13443):
Right now i am using following encoding for JSON parsing:-
NSString *requestString = [jsonstring UTF8String];
How can i parse Special character(Spanish Data) e.g Éspanol in JSON?
Any solution?
Thanks.
I was also having the same issue earlier with json. I solved this special character issue by using the following code:-
+(NSString *)http_post_method_changed:(NSString *)url content:(NSString *)jsonContent
{
NSURL *theURL = [NSURL URLWithString:url];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];
NSData *requestData = [jsonContent dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[theRequest setValue:#"application/json; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody: requestData];
NSURLResponse *theResponse = NULL;
NSError *theError = NULL;
NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
NSString *data=[[NSString alloc]initWithData:theResponseData encoding:NSUTF8StringEncoding];
NSLog(#"url to send request= %#",url);
NSLog(#"response1111:-%#",data);
return data;
}
Pass your url and json to send and it will provide you the desired response.
Did you use this?
NSArray *dataArray =
[NSJSONSerialization JSONObjectWithData:_data
options:NSJSONReadingAllowFragments
error:&error];
Make sure (by consulting the forsquare api docs) that the feed is indeed in UTF-8 - then the above should work without errors.
This assumes the API feed is sending you an array, use NSDictionary otherwise.

How to send the updated data using json to server in iphone?

am using web services (JSON). from json am getting data this data loading into tableview am trying to edit this data but after edit the data how to send this updated data to server.
please any one help me?
try this will help you.. this is the post method for updating data in WS .
NSString *post =[NSString stringWithFormat:#"uid=%#&firstname=%#&lastname=%#&phone=%#&bday=%#&about_me=%#&image=%#&image_code=%#&contact_number=%#",LoginID,fname,lname,cn,bday,abtme,strimage11,c11,cn];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"YOUR LINK"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *uData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:uData encoding:NSUTF8StringEncoding];
//
NSMutableDictionary *temp = [data JSONValue];
//
NSLog(#"%#",temp);
I am assuming you have your edited data, then
Form your json. There are several libraries out there which can help you.
Know the hostname of your server.
Know which API to hit on your server.
then pass this json as POST (GET is also ok, but POST is preferred).
Process this received json on your server.
Hope this helps. Nothing much to it actually.

xml parsing with Post method+iphone

I am having problem with xmlparsing with post method.
API URL : http://XXX.XXX.X.XX/api/user.php
Function Name : getUserList
Sample XML :
<root>
<data>
<id>0</id>
<search></search>
</data>
</root>
Now i am using :-
// setting up the URL to post to
NSString *urlString = #"http://XXX.XXX.X.XX/api/user.php";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
But how should i make the post HTMLbody part in this..
Means where and how should i put functional name and sample xml in the code
My Edited Question is :-
NSString *urlString = #" http://192.168.6.79/silverAPI/api/user.php/getUserList";
// setting up the request object now
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString * str = #"<root><data><id>0</id><search>a</search></data></root>";
NSString * message= [NSString stringWithFormat:#"/getUserList mydata=%#", str];
[request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"Responce==>%#",returnString);
But i getting black in responce.Pleaseee help me out..
is my
NSString *urlString = #" http://192.168.6.79/silverAPI/api/user.php/getUserList";
And
NSString * str =
#"0a";
NSString * message= [NSString stringWithFormat:#"/getUserList
mydata=%#", str];
[request setHTTPBody:[message
dataUsingEncoding:NSUTF8StringEncoding]];
[request addValue:#"application/xml; charset=utf-8"
forHTTPHeaderField:#"Content-Type"];
This part of code is correct??
You can set html body using method - (void)setHTTPBody:(NSData *)data. For example:
[request setHTTPBody:[message dataUsingEncoding:NSUTF8StringEncoding]];
where message is,in your case, xml.
Also you need to add this code to help server to determine type of sent data:
[request addValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
If you want to set some additional flags to your request you can use method - (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field.
What you have done is perfect, please check on server side whether response from there is coming properly by sending the same request or not.

How to set the format of JSON post method in iphone

I'm sending a post request through webservices but I'm not getting the response I want.
Here's my code:
NSString *newurlString = [NSString stringWithFormat:#"{\"name\":\"asit\",\"email\":\"m.kulkarni#easternenterprise.com\",\"businessType\":\"1\",\"score\":30}"];
NSString * url = #"http://www.nieuwe-dag.nl/mobile_be/public/?action=saveScore";
//NSString *urlString =[NSString stringWithFormat:#"name=%#&email=%#&businessType=%d&score=%d",name, email, bussinesstype, score];
NSData *postData = [newurlString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"urlString::%#",newurlString);
NSLog(#"postLength::%#",postLength);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:300];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection =[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection){
webData = [[NSMutableData data] retain];
}
else {
NSLog(#"theConnection is NULL");
}
You are setting the request type to json but you are not creating a json. The data you are creating is just nsstring. I think you need to create a json object. You can download JSON API from here:
https://github.com/stig/json-framework/
Use [SBJSONWriter dataWithObject:] to create a JSON object. Then pass it to your request.
FOr more info on JSON:
http://www.json.org/
You need proper postData
NSDictionary *dataDict = #{
#"name": #"asit",
#"email": #"m.kulkarni#easternenterprise.com",
#"businessType": #"1",
#"score": #(30)
};
NSData *postData = [NSJSONSerialization dataWithJSONObject:dataDict options:0 error:nil];

Fetch POST value in coldfusion from objective C

I am trying to post a string to a URL in iphone which will be retrieved by the server. The server side scripting is done in coldfusion. I am trying to fetch the data in coldfusion and pass on the value back to iphone. I am not familiar much with coldfusion and wanted some help in this. Below is the coding in iphone :
/** Iphone code **/
NSString *post =[[NSString alloc] initWithString:#"Hello World"];
NSURL *url=[NSURL URLWithString:#"http://www.abc.com/test.cfm"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
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];
/*Coldfusion code */
<html>
<head><title>Test</title></head>
<body>
<cfoutput>#form.post#</cfoutput>
</body>
</html>
Am I doing it correctly ?
You may need to specify name of form variable in data. Try below for post variable. I haven't tested it should work.
NSString *post =[[NSString alloc] initWithString:#"post=Hello%20World"];