我是iOS新手我想调用google api方向服务并解析它,我知道如何使用post方法调用web服务,但我不知道如何将参数集成到url中,并从中获取json响应。请帮我。
问问题
233 次
2 回答
1
要使用 Post 传递数据,NSURLConnection
您可以使用setHTTPBody
方法。
您可以使用以下代码:
NSURL *aUrl = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
delegate:self];
[request setHTTPMethod:@"POST"];
NSString *postString = @"username=Midhun&password=Midhun";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
并且可以通过didReceiveData
委托方法获取响应数据。您需要将接收到的数据附加到NSMutableData
对象以供进一步使用。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
于 2012-12-22T12:59:16.413 回答
1
请看下面的代码,你会有所了解。
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSString *stringOrigin = @"Surandai";
NSString *stringDestination = @"Coimbatore";
NSData *dataDirection = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=true", stringOrigin, stringDestination]]];
NSDictionary *dictionaryDirection = [NSJSONSerialization JSONObjectWithData:dataDirection options:NSJSONReadingAllowFragments error:nil];
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"dictionaryDirection - %@", dictionaryDirection);
//Do UI update here
});
});
于 2012-12-22T13:09:16.167 回答