json post request method - iphone

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.

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.

Objective-C equivalent of curl request

I'm trying to manipulate this curl request in Objective-C:
curl -u username:password "http://www.example.com/myapi/getdata"
I've implemented the following and I'm getting a data get error Domain=kCFErrorDomainCFNetwork Code=303 with NSErrorFailingURLKey=http://www.example.com/myapi/getdata:
// Make a call to the API to pull out the categories
NSURL *url = [NSURL URLWithString:#"http://www.example.com/myapi/getdata"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
// Create the username:password string for the request
NSString *loginString = [NSString stringWithFormat:#"%#:%#", API_USERNAME, API_PASSWORD];
// Create the authorisation string from the username password string
NSData *postData = [loginString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
I was hoping that someone could spot where I am going wrong with my attempt to manipulate the curl request and point me in the correct direction. Is there something obvious I'm missing out? The data returned from the API is in a JSON format.
I found that the best thing to do was to not attempt the authentication within the code and to put it straight in the URL itself. The working code looks as follows:
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:#"http://%#:%##www.example.com/myapi/getdata", API_USERNAME, API_PASSWORD]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
This guide seems to do what you're looking for:
http://deusty.blogspot.co.uk/2006/11/sending-http-get-and-post-from-cocoa.html
Just as an FYI, a lot of classes accept initWithData, and NSData has a method dataWithContentsOfURL, if you want to avoid setting up NSURLConnections yourself this could be an easier way of achieving what you're looking for.

iPhone:Http POST request

I need to send some details to a server from my iphone app.I have details as separate arrays of ID,name,quantity and strings with name,address,phone & email.I need to change the NSmutable array data into this JSON format
[
{"id":"139","name":"Samosa","quantity":"332","spice":"hot"},
{"id":"149","name":"rice","quantity":"4","spice":"mild"},
.....
]
My one doubt is [request setHTTPMethod:#"POST"];
Is the above line is enough to set the POST request.
How could I add the above details into the POST request?
Use a JSON serializer. You could use SBJSON. With SBJSON, the code will be like this:
SBJsonWriter *jsonWriter = [[[SBJsonWriter alloc] init] autorelease];
NSString *jsonParams = [jsonWriter stringWithObject:<your-NSArray>];
For adding this jsonParams to POST:
NSString *postData = [jsonParams stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:postURL];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];
Not enough. You need also (minimum):
NSString *your_request_string = #"the thing in JSON format";
NSData *your_data = [your_request_string dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:your_data];
Use setHTTPBody: to add post data to your HTTP request object.
Use NSJSONSerialization to serialize your array.
NSMutableArray *array = getSomeArray();
NSError *err;
NSData *json;
json = [NSJSONSerialization dataWithJSONObject:array options:0 error:&err];
if (err) {
// handle error
}
NSURL *url = getSomeURL();
NSMutableURLRequest *req;
req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:#"POST"];
[req setHTTPBody:json];
// send your request

NSMutableURLRequest loses session information

I have an iphone app that I'm trying to get to talk to a rails back end. I'm using NSMutableURLRequest to pull data back and forth. All the calls work fine on GET requests but when I need to post data, my rails app can't seem to find the session. I've posted the code below for both a get and a POST request.
This is the POST request:
//Set up the URL
NSString *url_string = [NSString stringWithFormat:#"https://testserver.example.com/players.xml"];
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
//To create an object in rails
//We have to use a post request
////This is the format when using xml
NSString *requestString = [[NSString alloc] initWithFormat:#"<player><team_game_id>%#</team_game_id><person_id>%#</person_id></player>", game, person];
NSData *requestData = [NSData dataWithBytes:[requestString UTF8String] length:[requestString length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//For some reason rails will not take application/xml
[request setValue:#"application/xml" forHTTPHeaderField:#"content-type"];
The get request is:
NSString *url_string = [NSString stringWithFormat:#"https://testserver.example.com/people/find_by_passport?passport=%i", passport];
passportString = [[NSMutableString alloc] initWithFormat:#"%i", passport];
NSLog(#"The passport string is %#", passportString);
NSLog(url_string, nil);
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
I am at my wits end here trying to find out whats going on so any help would be GREATLY appreciated.
Faced the same issue. Parse the response headers for the Set-Cookie header, extract the cookies by hand, pass them back as Cookie: header on subsequent requests.
If this is just about sessions in their simplest, you don't have to worry about persistence, HTTPS, domains/paths and such.
EDIT: I found class NSHTTPCookieStorage. See if it can be of help...

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.