iPhone:Http POST request - iphone

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

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.

JSON parsing, How to get response from server

I have the following details, for get the data from server. What is the use of methodIdentifier and web service name ?
{"zip":"12345","methodIdentifier":"s_dealer"}
url:- http://xxxxxxxxxxxxxxx.com/api.php
method: post
web service name: s_dealer
response : {"success":"0","dealer":[info...]}
I don't know how to send zip number "12345" with the url. Please direct me on right direction. I use the following.
-(void)IconClicked:(NSString *)zipNumber
{
NSString *post = [NSString stringWithFormat:#"&zipNumber=%#",zipNumber];
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:#"http://xxxxxxxxxxxxxxxxxxx.com/api.php"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
receivedData = [[NSMutableData alloc]init];
}
when i print the response in console :\"Unexpected end of string\"
Without knowing more about the API, I can't be certain about your requirements, but it seems that the server is expecting the request to contain JSON. The way you currently are creating the body for the request is using standard POST variables.
Have you tried changing:
NSString *post = [NSString stringWithFormat:#"&zipNumber=%#",zipNumber];
to:
NSString *post = [NSString stringWithFormat:#"{\"zip\":\"%#\",\"methodIdentifier\":\"s_dealer\"}",zipNumber];
Regarding your other questions, I'm guessing that there is a single URL for the API. The methodidentifier is used by the server in order to determine which server method(s) to run.
You get this error because you do not get a json as a response, but an error from Apache (or whatever), that has different structure, and json cannot parse it. Try my method to initiate the connection, in order to gain a successful one.
Declare a NSURLConnection property and synthesize it. Now:
NSString *post = [NSString stringWithFormat:#"zipNumber=%#",zipNumber];
NSString *toServer = [NSString stringWithString:#"your server with the last slash character"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#api.php?", toServer]];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[urlRequest setURL:url];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setValue:#"utf-8" forHTTPHeaderField:#"charset"];
[urlRequest setHTTPBody:postData];
[urlRequest setTimeoutInterval:30];
NSURLConnection *tmpConn = [[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self] autorelease];
self.yourConnectionProperty = tmpConn;
Now you work with self.yourConnectionProperty in connection delegates. Cheers!
hey bro check my answer for same problem may help you... You have to use the NSURLConnection Delegates to get the data
Could not make Json Request body from Iphone

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

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.