//發(fā)送GET 同步請(qǐng)求
- (void)sendSynNetWorking{
//創(chuàng)建urlString
NSString *urlString = @"http://api2.juheapi.com/xiecheng/senicspot/ticket/search?key=815a3cbd22f9127bc8d3d8e1076f7b32&pageindex=1&pagesize=20&keyword=%E6%88%90%E9%83%BD";
//創(chuàng)建URL
NSURL *url = [NSURL URLWithString:urlString];
//創(chuàng)建請(qǐng)求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *error = nil;
//發(fā)送請(qǐng)求
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
//把NSData轉(zhuǎn)成JSON
id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(@"%@",object);
}
//發(fā)送POST 異步請(qǐng)求
- (void)sendAsynWithPostNetWorking{
//先配置請(qǐng)求參數(shù)
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:@"1" forKey:@"pageindex"];
[dictionary setObject:@"5" forKey:@"pagesize"];
[dictionary setObject:@"上海" forKey:@"keyword"];
[dictionary setObject:@"" forKey:@"key"];//填入api的key
//
NSMutableString *string = [NSMutableString string];
for (NSString *key in dictionary) {
[string appendFormat:@"%@=%@&",key,dictionary[key]];
}
//轉(zhuǎn)成DATA
NSData *body = [string dataUsingEncoding:NSUTF8StringEncoding];
//創(chuàng)建urlString
NSString *urlString = @"http://api2.juheapi.com/xiecheng/senicspot/ticket/search?";
//創(chuàng)建URL
NSURL *url = [NSURL URLWithString:urlString];
//創(chuàng)建請(qǐng)求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:body];
//發(fā)送請(qǐng)求
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"%s",__FUNCTION__);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"得到響應(yīng)");
self.data = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"接受數(shù)據(jù)");
[self.data appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"數(shù)據(jù)接受完成");
//? ? NSLog(@"%@",self.data);
//把NSData轉(zhuǎn)成JSON
id object = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",object);
}