iOS 網路NSURLConnection,iosnsurlconnection

來源:互聯網
上載者:User

iOS 網路NSURLConnection,iosnsurlconnection

  • NSURLRequest

    • 用於儲存請求地址/要求標頭/請求體
    • 預設情況下NSURLRequest會自動給我們設定好要求標頭
    • request預設情況下就是GET請求
  • NSURLConnection和RunLoop
    • 預設情況會將NSURLConnection添加當前線程到RunLoop,如果是在子線程中調用NSURLConnection可能會有問題, 因為子線程預設沒有RunLoop

    • 如何讓代理方法在子線程中執行?

      • [conn setDelegateQueue:[[NSOperationQueue alloc] init]];
    • 注意:

      • NSURLConnection是非同步請求

      •   // 1.發送請求  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://XXXXX/resources/images/minion_01.png"]] ; NSRunLoop *runloop = [NSRunLoop currentRunloop]; NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];  [conn setDelegateQueue:[[NSOperationQueue alloc] init]];  // 2.啟動runLoop  // 預設情況下子線程沒有RunLoop, 所以需要啟動  [runloop run];  // 3.如果手動發送請求, 系統內部會自動幫子線程建立一個RunLoop//    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];//    [conn start];

         

  • 同步請求

    • 如果是調用NSURLConnection的同步方法, 會阻塞當前線程
    • // 1.建立一個URL    NSURL *url = [NSURL URLWithString:@"http://XXXXXXX/login?username=XXX&pwd=XXX&type=JSON"];    // 2.根據URL建立NSURLRequest對象    NSURLRequest *request = [NSURLRequest requestWithURL:url];    // 3.利用NSURLConnection對象發送請求    /*     第一個參數: 需要請求的對象     第二個參數: 服務返回給我們的回應標頭資訊     第三個參數: 錯誤資訊     傳回值: 伺服器返回給我們的響應體     */    NSHTTPURLResponse *response = nil; // 真實類型    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];    NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);    NSLog(@"response = %@", response.allHeaderFields);
  • 非同步請求
    • // 1.建立一個URL    NSURL *url = [NSURL URLWithString:@"http://XXXXX/login?username=XXX&pwd=XXX&type=JSON"];    // 2.根據URL建立NSURLRequest對象    NSURLRequest *request = [NSURLRequest requestWithURL:url];    // 3.利用NSURLConnection對象發送請求    /*     第一個參數: 需要請求的對象     第二個參數: 回調block的隊列, 決定了block在哪個線程中執行     第三個參數: 回調block     */    // 注意點: 如果是調用NSURLConnection的同步方法, 會阻塞當前線程    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);    }];
  • POST方法
    • // 1.建立一個URL    NSURL *url = [NSURL URLWithString:@"http://XXXXX/login"];    // 2.根據URL建立NSURLRequest對象    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    // 2.1佈建要求方式    // 注意: POST一定要大寫    request.HTTPMethod = @"POST";    // 2.2佈建要求體    // 注意: 如果是給POST請求傳遞參數: 那麼不需要寫?號    request.HTTPBody = [@"username=XXX&pwd=XXX&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];    // 3.利用NSURLConnection對象發送請求    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);    }];
  • 請求伺服器響應
    • // 1.建立URL    NSURL *url = [NSURL URLWithString:@"http://XXXXX/resources/images/minion_02.png"];    // 2.根據URL建立NSURLRequest    NSURLRequest *request = [NSURLRequest requestWithURL:url];    // 3.利用NSURLConnection發送請求    /*    // 只要調用alloc/initWithRequest, 系統會自動發送請求    [[NSURLConnection alloc] initWithRequest:request delegate:self];    */    /*    // startImmediately: 如果傳遞YES, 系統會自動發送請求; 如果傳遞NO, 系統不會自動發送請求    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];    [conn start];    */    [NSURLConnection connectionWithRequest:request delegate:self];
       
  •  代理方法
    • #pragma mark - NSURLConnectionDataDelegate/* 只要接收到伺服器的響應就會調用 response:回應標頭 */- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{    NSLog(@"%s", __func__);}/*  接收到伺服器返回的資料時調用(該方法可能調用一次或多次)  data: 伺服器返回的資料(當前這一次傳遞給我們的, 並不是總數) */- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{    NSLog(@"%s", __func__);}/* 接收結束時調用 */- (void)connectionDidFinishLoading:(NSURLConnection *)connection{    NSLog(@"%s", __func__);}/* 請求錯誤時調用(請求逾時) */- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{    NSLog(@"%s", __func__);}
  • 中文問題
    • // 1.建立URL    NSString *urlStr = @"http://XXXXXX/login2?username=部落格園&pwd=XXX&type=JSON";    NSLog(@"轉換前:%@", urlStr);    // 2.對URL進行轉碼    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

       

相關文章

聯繫我們

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