ios網路學習------1get post非同步請求

來源:互聯網
上載者:User

標籤:des   class   blog   code   http   tar   

網路請求的步驟:

get請求:

#pragma mark  - 這是私人方法,盡量不要再方法中直接使用屬性,因為一般來說屬性都是和介面關聯的,我們可以通過參數的方式來使用屬性#pragma mark Get登入方法- (void)loginWithGet:(NSString *)name pwd:(NSString *)pwd{    //1確定地址NSURL    NSString *urlString = [NSString stringWithFormat:@"www.baidu.com?username=%@&password=%@", name, pwd];    NSLog(@"%@",urlString);    //url中,如果包含中文字元需要轉換成帶百分比符號的格式,提供給伺服器解碼(如果伺服器用的是utf-8)。    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    NSLog(@"%@",urlString);    NSURL *url = [NSURL URLWithString:urlString];    //2建立請求NSURLRequest    NSURLRequest *request = [NSURLRequest requestWithURL:url];    //3建立並啟動串連NSRULConnection    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];    [conn start];  //啟動串連,這是網路請求已經發生了。這是一個非同步串連請求,,請求發送出去以後,就交由代理處理。        //伺服器通知準備,準備中轉資料    self.serverData = [NSMutableData data];}

post請求:

- (void)login{    NSLog(@"come here");    NSString *userName = self.nameTextField.text;    NSString *pwd = self.passwordTextField.text;    //[self loginWithGet:userName pwd:pwd];   //用get的方式調用        //上面一行是get方式,下面是post方式。    //1確定地址NSURL    NSString *urlString = [NSString stringWithFormat:@"www.baidu.com"];    NSURL *url = [NSURL URLWithString:urlString];        //2建立請求NSMutableURLRequest(post需要用這個)    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    //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];  //啟動串連,這是網路請求已經發生了。這是一個非同步串連請求,,請求發送出去以後,就交由代理處理。        //伺服器通知準備,準備中轉資料    self.serverData = [NSMutableData data];}



start以後,通過代理<NSURLConnectionDataDelegate>來實現後續的處理:

//4通過代理方法處理網路請求,遵守協議#pragma mark  網路資料處理代理,總共有五個代理方法#pragma mark  代理方法1   接受到伺服器的響應,伺服器要傳資料了,用戶端做好接收準備- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{    }#pragma mark   代理方法2  接收伺服器傳輸的資料,可能會多次執行- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{     //對每次傳輸的資料進行拼接,需要中轉資料    [self.serverData appendData:data];}#pragma mark   代理方法3  接收資料完成,做後續處理- (void)connectionDidFinishLoading:(NSURLConnection *)connection{     //對方法2拼接的資料,做後續處理。    NSString *str = [[NSString alloc] initWithData:self.serverData encoding:NSUTF8StringEncoding];            //對伺服器返回的字串進行處理。    //1 從str中找出的使用者名稱所在的位置    NSRange range = [str rangeOfString:@"使用者名稱"];  //nsrange存放尋找到的字串(使用者名稱)的位置和長度    NSLog(@"%@", NSStringFromRange(range));        NSString *msg = nil;    if (range.location > 0) {        //2曲使用者名稱後面的字串,一直到末尾        NSString *name = [str substringFromIndex:(range.location +range.length)];        NSLog(@"%@",name);        //3歡迎歸來        msg= [NSString stringWithFormat:@"歡迎歡迎:%@", name];    }else    {        msg = @"使用者名稱或者密碼錯誤,請重試!";    }        NSLog(@"%@", str);    //提示使用者登入成功    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];    [alertView show];        //清空資料    self.serverData = nil;}#pragma mark    代理方法4  f伺服器請求失敗,原因很多(w網路環境等等);-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{     NSLog(@"網路連接請求錯誤%@",error.localizedDescription); //本地化的錯誤資訊描述。}#pragma mark    d代理方法5  向伺服器發送資料,次方法僅適用於post,尤其上傳檔案。/* 第一個參數是串連,第二個參數是發送的資料體,第三個表示整體要寫的資料,第四個是表示預期要寫的資料。伺服器通過這些值知道這次傳了多少,已經傳了多少,預期總共要穿多少 */- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite{    NSLog(@"發送資料給伺服器");}@end


相關文章

聯繫我們

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