Passing Spanish Language Data through JSON - iphone

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.

Related

json post request method

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *encodedString = [jsonString base64EncodedString];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#wsName",baseUrl]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:encodedString forHTTPHeaderField:#"Data"];
This doesn't make sense. You're creating JSON, base-64 encoding it (you never have to base-64 encode JSON; if you were really trying to encrypt it, you have to come up with something better), and setting the header Data with this, while simultaneously providing a Content-Type informing the server that the request was XML, even though it wasn't.
If the server was expecting JSON, you'd just send JSON:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#wsName",baseUrl]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue: #"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
If the server was expecting XML, you'd use the text/xml or application/xml setting for Content-Type, but you'd also (a) have to construct the XML content; and (b) supply that to setHTTPBody.
If you wanted to secure the request, you'd use https://.
Bottom line, you must confirm what precisely the server is looking for. Don't guess, but rather look at the server's source code or documentation or talk to the developers. But your client-side code sample is unlikely to work as it stands.

How to Post xml within Json object in NSURLConnection?

Hi I want to post XML data within JSON Object.
This is the way i post
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSString *postString = [NSString stringWithFormat:#"{\"UserId\":\"%#\",\"UserDataXML\":\"%#\"}",#"USRfa9210bad85165d5",#"<Root Bookmark=\"Page1\">\\u000d\\u000a <Name>MyName<\Name>\\u000d\\u000a <Address>MyAddress<\ Address></Root>"];
NSData *requestData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:requestData];
In connectionDidFinishLoading _responseData is come,But responsedict is getting Null.
Where i am going wrong?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"_responseData %#",_responseData);
NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSError *error;
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"responseDict %#",responseDict);
}
First of all, you must escape your JSON before use.
And then,
(1) If the server is only responding with a form-data, a post data must be a pair of key and value.
NSString *postString = [NSString stringWithFormat:#"UserId=%#&UserDataXML=%#",
#"USRfa9210bad85165d5",
#"<Root Bookmark=\\\"Page1\\\">\\u000d\\u000a<Name>MyName</Name>\\u000d\\u000a<Address>MyAddress</Address></Root>"];
(2) If the server is only responding with JSON, Content-Type should be set to "application/json" and then,
NSString *postString = [NSString stringWithFormat:#"{\"UserId\":\"%#\", \"UserDataXML\":\"%#\"}",
#"USRfa9210bad85165d5",
#"<Root Bookmark=\\\"Page1\\\">\\u000d\\u000a<Name>MyName</Name>\\u000d\\u000a<Address>MyAddress</Address></Root>"];
BTW, have you checked the variable '_responseData'? I think it's also empty.

How to send a basic POST HTTP request with a parameter and display the json response?

I tried a lot of things but somehow not able to figure the basics of an HTTP POST request in ios. Sometimes I get a server error other times I get status code 200 but an empty response. The backend server code works and it is sending json data in response. Somehow my ios app is not able to get that response. Any help will be appreciated!
This is one of the things I tried! GetAuthorOfBook corresponds to a php server function that accepts strBookName as a POST argument and returns the name of author as a json object!
NSURL *url = [NSURL URLWithString:#"http://mysite.com/getAuthorOfBook"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *post = [NSString stringWithFormat:#"strBookName=Rework"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"gzip" forHTTPHeaderField:#"Accept-Encoding"];
[request setValue:#"text/html" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData ];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
The responseData should have the name of the author(strAuthorName) as a json "key":"value" pair.
The responseData isn't a json object yet. First you need to serialise it and assign it to an NSDictionary, then you can parse it by key.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
Now you should be able to access authorName by either this method (if it is just a string in the json):
NSString *authorName = [json objectForKey:#"strAuthorName"];
or like this if it is a dictionary of objects (an array of objects in the json)
NSDictionary *authorName = [json objectForKey:#"strAuthorName"];

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.

iPhone sending POST with NSURLConnection

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.