ios網路學習------2 用非代理方法實現非同步post請求

來源:互聯網
上載者:User

標籤:des   class   blog   code   http   tar   

#pragma mark  - 這是私人方法,盡量不要再方法中直接使用屬性,因為一般來說屬性都是和介面關聯的,我們可以通過參數的方式來使用屬性#pragma mark post登入方法-(void)loginWithPostWithName:(NSString *)userName pwd:(NSString *)pwd{    //1確定地址NSURL    NSString *urlString = [NSString stringWithFormat:@"www.baidu.com"];    NSURL *url = [NSURL URLWithString:urlString];        //2建立請求NSMutableURLRequest(post需要用這個)    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    //網路訪問逾時時間    [request setTimeoutInterval:2.0f];    //1)post請求方式,網路請求預設是get方法,所以如果我們用post請求,必須聲明請求方式。    [request setHTTPMethod:@"POST"];    //2)post請求的資料體,post請求中資料體時,如果有中文,不需要轉換。因為ataUsingEncoding方法已經實現了轉碼。    NSString *bodyStr = [NSString stringWithFormat:@"username=%@&password=%@", userName, pwd];    //將nstring轉換成nsdata    NSData *body = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];    NSLog(@"body data %@", body);    [request setHTTPBody:body];    //    //3建立並啟動串連NSRULConnection//    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];//    [conn start];  //啟動串連,這是網路請求已經發生了。這是一個非同步串連請求,,請求發送出去以後,就交由代理處理。        //3不用代理的同步請求,    NSURLResponse *response = nil;    NSError *error = nil;    //第二,三個參數是指標的指標,所有要用取址符,這個方法是同步方法。同步操作沒有完成,後面的代碼不會執行。    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];    //同步訪問的資料的後續處理    if (data != nil) {  //接受到資料,表示工作正常        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];        NSLog(@"%@", str);    }else if(data == nil && error != nil)    //沒有接受到資料,但是error為nil。。表示接受到空資料。    {        NSLog(@"接受到空資料");    }else{        NSLog(@"%@", error.localizedDescription);  //請求出錯。    }    //    //伺服器通知準備,準備中轉資料//    self.serverData = [NSMutableData data];}

相關文章

聯繫我們

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