IOS中的網路請求

來源:互聯網
上載者:User

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);         });              }];}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.