iOS 網路與多線程--4.同步Post方式的網路請求

來源:互聯網
上載者:User

標籤:

通過Post請求方式,同步擷取網路資料,一旦發送同步請求,程式將停止使用者互動,直至伺服器返回資料

在ViewController.m檔案內的viewDidLoad函數添加一下測試代碼

 1 - (void)viewDidLoad { 2     [super viewDidLoad]; 3     // Do any additional setup after loading the view, typically from a nib. 4      5     // 1.建立一個網址對象,指定請求資料的網址 6     NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"]; 7     // 2.再通過網址建立網路請求對象. 8     // 參數1:請求訪問路徑 9     // 參數2:緩衝協議10     // 參數3:網路請求逾時時間11     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];12     // 3.設定網路通訊方式為Post,預設為Get13     [request setHTTPMethod:@"POST"];14     // 4.設定網路請求的參數15     NSString *str = @"type=focus-c";16     // 5.將請求參數,轉換為位元據17     NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];18     [request setHTTPBody:data];19     // 6.使用網路連接對象實現網路通訊,網路連接對象建立成功後,就建立了一個網路連接。20     NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];21     // 7.將返回的資料轉換成字串並輸出22     NSString *str1 = [[NSString alloc] initWithData:received encoding:NSUTF8StringEncoding];23     NSLog(@">>>>>>>%@",str1);24 }

執行之後就可以根據指定網址擷取資料了。

iOS 網路與多線程--4.同步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.