NSURLSession的GET和POST下載

來源:互聯網
上載者:User

標籤:

/*     X-Code7NSURLConnection已經被棄用了,官方建議使用NSURLSession(ios7之後就已經出現了),在NSURLConnection的基礎上進行的封裝          */#if 0    NSString * path = @"http://10.0.8.8/sns/my/user_list.php?number=10&page=2";    //如果有參數 在URL後面用?串連起來  參數 = 具體的資料    //多個參數 用&串連起來    //如果是直接在URL後面加上參數  這種事get請求  預設就是get請求    NSURL * url = [NSURL URLWithString:path];        //請求類對象    NSURLRequest * request = [NSURLRequest requestWithURL:url];    //NSURLSession對象    NSURLSession * session = [NSURLSession sharedSession];    //NSURLSession資料任務 網路連接    NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {               if (!error) {            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];            NSLog(@"%@",obj);        }else{            NSLog(@"%@",error);        }    }];    //啟動任務  啟動下載    [task resume];#else        NSString * path = @"http://10.0.8.8/sns/my/user_list.php";        NSURL * url = [NSURL URLWithString:path];        NSMutableURLRequest * request = [[NSMutableURLRequest alloc]initWithURL:url];    //如果不設定 預設就是get    //佈建要求的方式    request.HTTPMethod = @"POST";    //不能在URL後面直接拼它的參數        //需要把參數寫到請求的body裡    NSString * str = @"number=10&page=2";    //佈建要求的body    request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding];        NSURLSession * session = [NSURLSession sharedSession];        NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {                if (!error) {            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];            NSLog(@"%@",obj);        }else{            NSLog(@"%@",error);        }    }];        [task resume];    #endif

 

NSURLSession的GET和POST下載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.