//發送GET 同步請求
- (void)sendSynNetWorking{
//創建urlString
NSString *urlString = @"http://api2.juheapi.com/xiecheng/senicspot/ticket/search?key=815a3cbd22f9127bc8d3d8e1076f7b32&pageindex=1&pagesize=20&keyword=%E6%88%90%E9%83%BD";
//創建URL
NSURL *url = [NSURL URLWithString:urlString];
//創建請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *error = nil;
//發送請求
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
//把NSData轉成JSON
id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(@"%@",object);
}
//發送POST 異步請求
- (void)sendAsynWithPostNetWorking{
//先配置請求參數
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]];
}
//轉成DATA
NSData *body = [string dataUsingEncoding:NSUTF8StringEncoding];
//創建urlString
NSString *urlString = @"http://api2.juheapi.com/xiecheng/senicspot/ticket/search?";
//創建URL
NSURL *url = [NSURL URLWithString:urlString];
//創建請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:body];
//發送請求
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"%s",__FUNCTION__);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"得到響應");
self.data = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"接受數據");
[self.data appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"數據接受完成");
//? ? NSLog(@"%@",self.data);
//把NSData轉成JSON
id object = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",object);
}