views:

465

answers:

2

Hello community

I don't have any idea how to post a JSON RPC request using Obj-C. Can anyone help me?

So far I have:

responseData = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://*************/services/json-rpc"]];

NSString *jsonString = @"{\"jsonrpc\": \"2.0\",\"method\": \"node.get\", \"params\": { \"arg1\": 1 } ,\"id\": \"dsadasdas\"}";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding];

[ request setHTTPMethod: @"POST" ];
[ request setHTTPBody: jsonData ];
[ request setValue:@"application/json" forHTTPHeaderField:@"Content-> Type"];

[[NSURLConnection alloc] initWithRequest:request delegate:self];

I'm using drupal + services + Json Server & JSON rpc server.

Seems I'm getting better results with the first one, the problem is building the body of the post i Think...

Please help me.

+1  A: 

This fixed it:

SBJSON *json = [SBJSON new];
json.humanReadable = YES;
NSString *service = @"node.get";

NSMutableDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                               @"1",@"nid",
                               nil];
//Pass it twice to escape quotes
NSString *jsonString = [NSString stringWithFormat:@"%@", [params JSONFragment], nil];
NSString *changeJSON = [NSString stringWithFormat:@"%@", [jsonString JSONFragment], nil];

NSLog(jsonString);
NSLog(changeJSON);


NSString *requestString = [NSString stringWithFormat:@"method=node.get&vid=1",service,changeJSON,nil];
NSLog(requestString);


NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://******************/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);
Xavi Colomer
A: 

Hey, I'm trying to do a similar thing, got the code to work, but for some reason it only seems to work with the "page" and "story" node types. With the other types of nodes the I created with CCK, it throws an error

did fail with error Error Domain=NSURLErrorDomain Code=-1005 UserInfo=0xf15390 "lost network connection"

can't figure out why, any ideas?