Json Request in iphone - iphone

Actually I am working on the Couchdb .Till now i have used the Local server for Connecting to he CouchDb . Now I need to Connect to the remote server of couchdb . For this I need to send the User Name And Password Through the Json .
How can we use authenticated basic Json post ?

use the post method (post the username and password )
code like …. try
NSString *postStr = [NSString stringWithFormat:#"username=%#&password=%#", username, password];
NSData *postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *requesting = [[NSMutableURLRequest alloc] initWithURL:YourURLObject];
[requesting setHTTPMethod:#"POST"];
[requesting setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[requesting setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[requesting setHTTPBody:postData];
NSError *error;
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:requesting returningResponse:&response error:&error];

Add JSON framework if you are using iOS5 sdk else download SBJSON and add it to your project and import "SBJSON.h"
Case 1: Using JSON Array
NSArray *credentials = [NSArray arrayWithObjects:#"uName", #"pWord",nil];
NSString *jsonString = [credentials JSONString];
Case 2: Using JSON Dictionary
NSDictionary *credentials = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"uName", #"pWord",nil] forKeys:[NSArray arrayWithObjects:#"UserName",#"password",nil]];
NSString *jsonString = [credentials JSONString];

Related

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.

How to get data from a json-rpc webservice : iPad /iPhone / Objective C

I'am working on a iPad project and this project needs to talk to a json-rpc webservices. The webservices is based on Drupal with module : cck and views
1)I need to push a json object into the webservice
2)I need the callback data from the webservice
I already have implemented the SBJSON api and the https://github.com/samuraisam/DeferredKit/ api to the iPad project.
The SBJSON api works fine and I understand this one
The Samuriaisam DefferedKit is new for me
My question is how to get data out of this json-rpc webservice, has someone some sample code? Or some places where I can find Objective C - json-rpc webservice documentation.
Kind Regards,
Bart Schoon
---------Update--------
I use this code now:
NSString *jsonString = #"{\"method\":\"views.get\",\"params\":{\"view_name\":\"client_list\",\"sessid\":\"xxxxxx\"},\"id\":1}";
NSString *requestString = [NSString stringWithFormat:#"%#",jsonString,nil];
NSLog(#"input: %#",jsonString);
NSData *requestData = [NSData dataWithBytes: [jsonString UTF8String] length: [jsonString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:#"http://subdomain.domain.com/services/json-rpc"]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:#"Content-type: application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:requestData];
//Data returned by WebService
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"output: %#",returnString);
This will result in this message from the server:
{"error":{"name":"JSONRPCError","code":-32600,"message":"The received JSON not a valid JSON-RPC Request"},"version":"1.1"}
---------/Update--------
What is wrong? Has someone experience with this?
Kind Regards,
Bart Schoon
Read JSon file get that data.
NSDictionary *dictionary = [jsonString JSONValue];
You will get key & value pair. Store that data in your respective variable.
-(IBAction)testCall{
NSString *requestString = [NSString stringWithFormat:#"method=views.get&view_name=client_list",nil];
NSLog(requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://.xxxxxxxxx.nl/services/json"]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
//Data returned by WebService
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(returnString);
NSDictionary *dict = [returnString JSONValue];
}
Just don't use a json-rpc - keep it simple and json the normal jSon method ;)

How i use Php in iphone

I am new in iphone,in my app required data from the server.
1)mysql database uploaded on the server
2)With the help of php code i fetch the data from the server
problem is that how i integrate php in my iphone please solve my problem,
give any reference.
Thanks,
I'm not sure to understand your problem, but you can't use PHP on iPhone.
If you need data from an external database, create web services to get the data in JSON, XML, or what suits you best.
Your iPhone application will connect to a specific URL, and get the data from a (PHP) script that will query the database and return the result in a specific format.
The best way in my opinion is to use JSON (see http://code.google.com/p/json-framework/).
You can make requests to your server using this code
NSError *error;
NSString *post =[NSString stringWithFormat:#"any-data=%#",
myData];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://your-server.com/your-script.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Data: %#",data);
NSDictionary* parsedData = [data JSONValue];
You then can access the data using
[parsedData valueForKeyPath:#"myVar"]
Hope this hepls,
Miguel
You could look at passing arrays of objects from the server to the iPhone in the form of a plist file. Have the server generate the plist in the appropriate format on a url and then on the device:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfURL:[NSURL URLWithString:#"http://www.example.com/myplist.php"];
NSArray *array = [NSArray arrayWithContentsOfURL:[NSURL URLWithString:#"http://www.example.com/myplist.php"];
If your unsure what the format is for plist files create one in your xcode project and use that as a template.