標籤: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];}