iPhone + Drupal + JSON RPC Server problem - iphone

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.

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

Related

Add new place to Google Places

I am new to IOS. I have to add new places to Google Places. I have referred this link https://developers.google.com/places/documentation/actions to add a place on button click, but I'm confused about passing parameters for this.
My coding lines are like this to fetch:
NSString *lat =#"-33.8669710";
NSString *longt =#"151.1957362";
gKey = #"my api key";
NSString *placeString = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/add/json?sensor=false&key=%#HTTP/1.1Host:maps.googleapis.com {\"location\":{\"lat\":%#,\"lng\":%#},\"accuracy\": 50,\"name\":\"Gimmy Pet Store!\",\"types\":[\"pet_store\"],\"language\":\"en-AU\"}",gKey,lat,longt];
placeString = [placeString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Main Place Url: %#",placeString);
NSURL *placeURL = [NSURL URLWithString:placeString];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:placeURL];
[request setHTTPMethod:#"POST"];
NSURLConnection *placesConn =[[NSURLConnection alloc] initWithRequest:request delegate:self];
I have made following changes to my code & finally it is executed successfully...
//for setting Parameters to post the url.just change tag values to below line...
NSString *str1 = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><PlaceAddRequest><location><lat>your latitude</lat><lng>your longitude</lng></location><accuracy>50</accuracy><name>place name</name><type>supported type</type><language>en-US</language></PlaceAddRequest>"];
NSLog(#"str1=====%#",str1);
NSString *str2 = [str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *requestdata = [NSData dataWithBytes:[str2 UTF8String] length:[str2 length]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestdata length]];
//requesting main url to add new place to google places
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/add/xml?sensor=false&key=your api key"]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:[str1 UTF8String] length:[str1 length]]];
//NSURLConnection *placesConn =[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *returndata = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnstr = [[[NSString alloc] initWithData:returndata encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"returnstr: %#",returnstr);
& then i have decoded return response which i get i status as OK......:)
Any one can use above code...if any help require you can surely ask....:)

URL Decoding of json in ios

I am having 1 webservice in php which is having browser url mentioned bel :
http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01 01:00:00
Now when I try to fetch url in my iphone app, it is taking this url:
http://Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00
This is creating problem.
i have used this code for fetching data from my url.
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"";
NSString *str;
str = #"LastUpdated";
NSString *requestString = [NSString stringWithFormat:#"{\"LastUpdated\":\"%#\"}",str];
// [[NSUserDefaults standardUserDefaults] setValue:nil forKey:#"WRONGANSWER"];
NSLog(#"request string:%#",requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:#"URL"];
//urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL : %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"Resp : %#",responseString);
if (respError)
{
// NSString *msg = [NSString stringWithFormat:#"Connection failed! Error - %# %#",
// [respError localizedDescription],
// [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ACTEC"
message:#"check your network connection" delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{
......
}
here,i am getting null response as url is getting decoded...How can I make this solved...
Help me out.
Thanks in advance.
NSString *urlLoc = [[fileContents objectForKey:#"URL"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableData *postData = [NSMutableData data];
NSMutableURLRequest *urlRequest;
[postData appendData: [[NSString stringWithFormat: #"add your data which you want to send"] dataUsingEncoding: NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:urlLoc]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSString *temp = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"\n\nurl =%# \n posted data =>%#",urlLoc, temp);
check nslog. that which data u send to service.
NSData *response = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"json_string >> %#",json_string);
Maybe this will help you.
hey dear just for an another example i just post my this code..
first Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:
    [NSURL URLWithString:#"http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00"]];
Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request
    returningResponse:nil error:nil];
Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc]
    initWithData:response encoding:NSUTF8StringEncoding];
Parse the JSON response into an object Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil]
And in statuses array you have all the data you need.
i hope this help you...
:)

converting image to base64 and uploading in JSON format to server

I have a problem. I need to convert base64 string to JSON string and pass it to server.
for example I have a base64 string /9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/Z
i need to convert it to JSON format. I do the following:
+(NSData *)prepareForUploading:(NSString *)base64Str
{
NSDictionary *dict=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:base64str, nil] forKeys:[NSArray arrayWithObjects:#"picture", nil]];
NSData *preparedData=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
return preparedData;
};
here how I'm making NSURLRequest
-(NSString *)uploadPict:(NSString *)pict
{
NSLog(#"Server: upload: called");
NSData *prepPictData=[[self class] prepareForUploading:pict];
NSString *preparedBase64StrInJSON=[[NSString alloc] initWithData:prepPictData encoding:NSUTF8StringEncoding];
//here I'm adding access token to request
NSString *post = [NSString stringWithFormat:#"accessToken=%#&object=%#", self.key, preparedBase64StrInJSON];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#upload.aspx", serverAPIPath]]];
[request setHTTPMethod:#"POST"];
[request setValue:#"postLength" forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//....
}
But I get "Invalid length for a Base-64 char array" from server. What's wrong?
If I paste my token and JSON to http://hurl.it/ and make request using it - everything goes normally.
I think the problem is / symbols in base64 string and as a result / symbols in JSON.
Maybe it is something with [postData length]: if I erase \/ characters from JSON string:
9j4AAQSkZJRgABAQAAAQABAAD4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQHZ request will perform normally but this base64 encoded string is not the same.
Please, help me to solve this problem
jString is your base64 string, first use following line
[self encodeString:jString];
and then call use following.
NSString *URL = [NSString stringWithFormat:#"forms.asmx/CreateUpdate?"];
URL=[NSString stringWithFormat:#"%#%#", USERS_API_ROOT_URL, URL];
NSString *post = [NSString stringWithFormat:#"apiKey=A0B1I2L3A4L5-A1D3-4F30-5AB2-C8DEE266&strPost=%#",jString];
unsigned long long postLength = [post length];
NSString *contentLength = [NSString stringWithFormat:#"%llu",postLength];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData ];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
-(NSString *)encodeString:(NSString *)string
{
NSString *newString = (__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL,CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
return newString;
}
Hope it will work.

Iphone Http request response using json

I am trying to send the data to server and get the response. Data is reaching server but I am not getting any response. The value of response data is nil bcd of which it's throwing an exception,
-JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=11 \"Unexpected end of string\" UserInfo=0x4e2dd70 {NSLocalizedDescription=Unexpected end of string}"
Can anyone pls help me....
My code:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.0.83:8082/WebServiceProject/AcessWebservice?operation=login"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSError *theError = NULL;
NSArray *keys = [NSArray arrayWithObjects:#"UserId", #"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:#"rajin.sasi", #"abhi1551", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString* jsonString = [jsonDictionary JSONRepresentation];
SBJSON *jsonParser = [SBJSON new];
[jsonParser objectWithString:jsonString];
NSLog(#"Val of json parse obj is %#",jsonString);
[request setHTTPMethod:#"POST"];
[request setValue:jsonString forHTTPHeaderField:#"json"];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
[request setHTTPBody:responseData];
NSMutableString* stringData= [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *jsonDictionaryResponse = [stringData JSONValue];
NSString *json_message=[jsonDictionaryResponse objectForKey:#"message"];
printf("Json string is %s **********",[json_message UTF8String]);
I'm not privy of the particulars of your webservice, but the code below might be the source of your problem (or at least one of them!)
[request setValue:jsonString forHTTPHeaderField:#"json"];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
[request setHTTPBody:responseData];
You are sending the request before setting the body, which I assume should include your jsonString contents. Plus you're assigning your jsonString to a header field, are you sure that is what you want? Here's a guess at what might work:
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody:jsonString];
responseData = // rest of your code here....
I suggest you have a good look through that code as it is a mess at the moment! You have two NSURLConnection requests going there, one asynchronous and one synchronous, it's kind of hard to understand what/why you are doing all of this so check Apple's documentation for NSURLConnection and tidy up your code...
[EDIT]
Here's my suggestion for you:
NSError *theError = nil;
NSArray *keys = [NSArray arrayWithObjects:#"UserId", #"Password", nil];
NSArray *objects = [NSArray arrayWithObjects:#"rajin.sasi", #"abhi1551", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *jsonString = [jsonDictionary JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.0.83:8082/WebServiceProject/AcessWebservice?operation=login"]];
[request setValue:jsonString forHTTPHeaderField:#"json"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
NSMutableString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonDictionaryResponse = [string JSONValue];
[string release];
[theResponse release];
NSData* responseData = nil;
NSURL *url=[NSURL URLWithString:[URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
responseData = [NSMutableData data] ;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *bodydata=[NSString stringWithFormat:#"%#",jsonString];
NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:req];
[request setTimeoutInterval:15.0];
NSURLResponse* response;
NSError* error = nil;
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSError *dataError;
NSMutableDictionary * jsonDict = [[NSMutableDictionary alloc]init];
if (responseData != nil)
{
jsonDict = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&dataError];
NSLog(#"jsonDict:%#",jsonDict);
}
Try this :
[request setValue:jsonString forHTTPHeaderField:#"json"];
responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&theError];
[request setHTTPBody:responseData];

Google Reader Token Request giving 403 error

I am trying to get the token from google reader for my iPhone project. I am able to get the Authorization but when I request for the token, I get a 403 Forbidden
Below is my code implementation. Any help would be appreciated.
//The tokenStorer contains the Authorization key
NSString *tokenStorer = [[NSUserDefaults standardUserDefaults]valueForKey:#"authKey"];
NSLog(#"%#", tokenStorer);
NSDictionary *cookieDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"www.google.com", #"Host",
#"iReader", #"User-Agent",
#"gzip, deflate", #"Accept-Encoding",
tokenStorer, #"Authorization",
nil
];
//#"Auth", NSHTTPCookieName, tokenStorer, NSHTTPCookieValue, #"./google.com", NSHTTPCookieDomain, #"/", NSHTTPCookiePath, nil];
//NSHTTPCookie *authCookie = [NSHTTPCookie cookieWithProperties:cookieDictionary];
//Google token url "http://www.google.com/reader/api/0/token?client=clientName"
NSURL *url=[[NSURL alloc] initWithString:GOOGLE_READER_TOKEN_URL];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:url];
[urlRequest setHTTPMethod:#"GET"];
[urlRequest setAllHTTPHeaderFields:cookieDictionary];
NSData *reciveData;
NSURLResponse *response;
NSError *error;
reciveData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSMutableURLRequest *tokenRequest= [[NSMutableURLRequest alloc] initWithURL:url];
NSString *trial = [[NSString alloc]initWithData:reciveData encoding:NSASCIIStringEncoding];
NSLog(#"%# %d",trial, response);
[url release];
The below code solved my problem:
-(id)queryLoginDetails {
//authKey returns the authorization key
NSString *tokenStorer = [[NSUserDefaults standardUserDefaults]valueForKey:#"authKey"];
NSLog(#"%#", tokenStorer);
NSString *auth = [[NSString alloc] initWithString:
[NSString stringWithFormat:#"GoogleLogin auth=%#", [tokenStorer substringToIndex:[tokenStorer length]-1]]];
NSDictionary *createHeader = [[NSDictionary dictionaryWithObjectsAndKeys:#"www.google.com", #"Host", #"iReader", #"User-Agent", #"gzip, deflate", #"Accept-Encoding", auth, #"Authorization", nil]retain];
NSURL *url =[NSURL URLWithString:GOOGLE_READER_TOKEN_URL];
NSData *recieveData;
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:url];
[urlRequest setHTTPMethod:#"GET"];
[urlRequest setAllHTTPHeaderFields:createHeader];
NSURLResponse *response;
NSError *error;
recieveData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
NSString *myString = [[NSString alloc]initWithData:recieveData encoding:NSASCIIStringEncoding];
return myString;
}