I need to send request like this:
"http://api.site.com/login?q={"meta":{"api_key":"cb2f734a14ee3527b3"},"request":{"id":"username@host.name","password":"passw0rd"}}`
...the response to which should look like {"id":399205,"token":"d43f8b2fe37aa19ac7057701"}
To do so, I have tried the following code:
self.responseData = [NSMutableData data];
NSDictionary *apiKeyDict = [NSDictionary dictionaryWithObject:@"cb2f734a14ee3527b3" forKey:@"api_key"];
NSDictionary *idPasswordDict = [NSDictionary dictionaryWithObjectsAndKeys:@"tc-d@gmail.com",@"id", @"abc",@"password", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:apiKeyDict, @"meta", idPasswordDict, @"request", nil];
NSURL *url = [NSURL URLWithString:@"http://api.site.com/login?="];
NSError *error = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
self.recievedData = [NSMutableData data];
}
Later on, I get in the following:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.recievedData appendData:data];
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
The response data comes back as "<h1>CHttpException</h1><p>wrong sign</p>
" As I understand, the way of adding json data to the current url is not appropriate in this case. Does anyone have advice on how I can fix this?
resolve my problem. Convert posted json to appended string to base url-string. that's how I did it:
NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSMutableString *dictString = [[NSMutableString alloc]initWithData:requestData encoding:NSUTF8StringEncoding];
[dictString insertString:@"http://api.site.com/login?q=" atIndex:0];
//don't know why but dictString contains a lot of @"\n" and spaces to present it nice-formated.
[dictString replaceOccurrencesOfString:@"\n" withString:@"" options:nil range:NSMakeRange(0, dictString.length)];
[dictString replaceOccurrencesOfString:@" " withString:@"" options:nil range:NSMakeRange(0, dictString.length)];
NSURL *url = [NSURL URLWithString:[dictString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
if it helps someone will appreciate tick near this issue=)