標籤:des blog http get 使用 資料
#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]; //這裡是非代理的非同步請求,非同步請求並不會阻止主線程的繼續執行,不用等待網路請結束。 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError * 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); //請求出錯。 } }];
同步方法用在最典型的地方時使用者登入的時候:使用者必須登入進去才執行其它操作。 非同步方法呼叫是網路請求完成以後,再更新頁面等等。
用代理方式或者非代理方式的唯一區別是在網路請求的第三部,就是nsurlconnecttion中。。。其它都是一樣的,,,一個是通過代理來實現,一個是通過nsurlconnection的兩個類方法來實現,其它都是一樣的。
NSURLRequest的緩衝策略:
//2建立請求NSURLRequest //緩衝側虐 //逾時時間長度 NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f];
用緩衝策略的好處是一進入應用就可以進入頁面,即使沒有連網。一般情況下用預設緩衝就可以了。這些緩衝是緩衝到記憶體中,如果需要儲存下來,還需要後續處理。