IOS中的網路請求
使用NSURLConnection的網路請求,最好定義一個類方法,在主線程中直接調用類方法擷取請求到的網路資料//構建類方法--請求網路+ (void)requestData:(NSString *)urlStr httpMethod:(NSString *)method params:(NSMutableDictionary *)params comletionHandle:(void (^)(id result))block{ //1.構建URL urlStr = [BASE_URL stringByAppendingString:urlStr]; NSURL *url = [NSURL URLWithString:urlStr]; //2.request構建 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.timeoutInterval = 60; request.HTTPMethod = method; //判斷請求方式 if ([method isEqualToString:@"GET"]) { //往URL後直接拼接 NSMutableString *paramsStr = [[NSMutableString alloc]initWithString:@"?"]; //拼接樣式 //拼接URL---》https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00SllYeF568jxC1082c39bc40_Vqyg&username=aaa&pass=bbb //迴圈拼接參數字典 for (int i = 0; i < params.count; i ++) { NSString *key = params.allKeys[i]; NSString *value = params[key]; //開始拼接= [paramsStr appendFormat:@"%@=%@",key,value]; //拼接&符號 //最後一個不再用&符號拼接 if (i < params.count-1) { [paramsStr appendFormat:@"&"]; } } //得到拼接後的URL(將主URL與拼接的URL 拼接在一起得到完整的URL) request.URL = [NSURL URLWithString:[urlStr stringByAppendingString:paramsStr]]; }else if ([method isEqualToString:@"POST"]){ //將參數添加到請求體中 NSMutableString *paramsStr = [[NSMutableString alloc]initWithString:@""]; for (int i = 0; i < params.count; i ++) { NSString *key = params.allKeys[i]; NSString *value = params[key]; //開始拼接 [paramsStr appendFormat:@"%@=%@",key,value]; if (i < params.count - 1) { [paramsStr appendFormat:@"&"]; } } //添加到請求體中 //將字串轉化為資料 NSData *data = [paramsStr dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPBody = data; } //3.開始請求網路 NSOperationQueue *queue = [[NSOperationQueue alloc]init]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if (connectionError) { NSLog(@"error----%@",connectionError); return ; } //成功擷取資料 //開始解析資料 id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; //返回資料 dispatch_async(dispatch_get_main_queue(), ^{ block(result); }); }];}