Get & Post請求
•網絡訪問的四個步驟
sendSynchronousRequest:request returningResponse:&response error:&error
sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
有關主操作隊列的內容,在多線程課程講解
同步請求數據會造成主線程阻塞,通常在請求大數據或網絡不暢時不建議使用。
從上面的代碼可以看出,不管同步請求還是異步請求,建立通信的步驟基本是一樣的:
1、創建NSURL
2、創建Request對象
3、創建NSURLConnection連接。
NSURLConnection創建成功后,就創建了一個http連接。異步請求和同步請求的區別是:創建了異步請求,用戶可以做其他的操作,請求會在另一個線程執行,通信結果及過程會在回調函數中執行。同步請求則不同,需要請求結束用戶才能做其他的操作。
(今天學習關于網絡的基礎,代碼有一些重復,緩存策略還沒有學習)
下面是get和post方式的代碼:
#pragma mark - 測試get方式-(IBAction)getLogin:(UIButton *)btn{ static NSString * loginUrl =@"http://192.168.1.102:8080/IOSApplication/LoginServletController.do"; //初始化數據 _receiveDate = [NSMutableData data]; //定義URL NSString * urlStr = [NSString stringWithFormat:@"%@?username=%@&passWord=%@",loginUrl,_userName.text,_password.text]; // 注意:網絡請求的URL,需要編碼才可以使用?。。 NSURL *url = [NSURL URLWithString:urlStr]; //// 定義請求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //定義連接 NSURLConnection *cont = [[NSURLConnection alloc] initWithRequest:request delegate:self]; [cont start];}#pragma mark - 網絡連接錯誤判斷-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ NSLog(@"網絡連接錯誤%@",error.localizedDescription);}#pragma mark - 接收響應- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSLog(@"開始接收的響應");}#pragma mark - 收到數據- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ NSLog(@"收到服務器返回的數據:%@",data); [_receiveDate appendData:data];}#pragma mark - 連接結束-(void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSString *backString = [[NSString alloc]initWithData:_receiveDate encoding:NSUTF8StringEncoding]; NSLog(@"結束接收的數據 %@",backString); _receiveDate = nil;}#pragma mark - 測試post方式-(IBAction)postLogin:(UIButton *)btn{ static NSString * loginUrl =@"http://192.168.1.102:8080/IOSApplication/LoginServletController.do"; //初始化數據 _receiveDate = [NSMutableData data]; // 定義URL,字母及數字組成的url不需要編碼 NSURL * url = [NSURL URLWithString:loginUrl]; //定義請求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //等待服務器響應時間5 [request setTimeoutInterval:5.0]; //設置請求方式 [request setHTTPMethod:@"post"]; NSString *bodyString = [NSString stringWithFormat:@"username=%@&password=%@",_userName.text,_password.text]; //生成請求數據并編碼 NSData *body = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; // 設置HTTP請求數據體,NSMutableURLRequest會自動在請求頭中加入Content-Length [request setHTTPBody:body]; //設置連接 NSURLConnection *cont = [[NSURLConnection alloc]initWithRequest:request delegate:self]; //開始連接 [cont start]; }#pragma mark - 發送數據給服務器,POST請求使用此方法- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite{ NSLog(@"發送數據給服務器 bytesWritten: %ld, totalBytesWritten %ld totalBytesExpectedToWrite %ld", bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);}
下面是同步和異步(NSURLConnection提供了兩個靜態方法可以直接同步或異步調用NSURLRequest,而無需通過NSURLConnectionDataDelegate獲取數據)
//生成post請求-(NSMutableURLRequest *)postLoginRequest{ static NSString * loginUrl =@"http://192.168.1.102:8080/IOSApplication/LoginServletController.do"; //初始化數據 _receiveDate = [NSMutableData data]; // 定義URL,字母及數字組成的url不需要編碼 NSURL * url = [NSURL URLWithString:loginUrl]; //定義請求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //等待服務器響應時間5 [request setTimeoutInterval:5.0]; //設置請求方式 [request setHTTPMethod:@"post"]; NSString *bodyString = [NSString stringWithFormat:@"username=%@&password=%@",_userName.text,_password.text]; //生成請求數據并編碼 NSData *body = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; // 設置HTTP請求數據體,NSMutableURLRequest會自動在請求頭中加入Content-Length [request setHTTPBody:body]; return request;}#pragma mark - post 同步方式登錄-(IBAction) synchronizationLogin:(UIButton *)btn{ NSMutableURLRequest *request = [self postLoginRequest]; NSError *error; NSURLResponse *response; NSDate * date = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; // 注意,只有同步請求結束之后,才會執行后續操作,修改LOGIN_URL可以看到效果 if (!date) { NSLog(@"同步訪問錯誤:%@",error.localizedDescription); } else{ //解碼數據 NSString *string = [[NSString alloc]initWithData:date encoding:NSUTF8StringEncoding]; NSLog(@"同步數據 %@",string); }}#pragma mark - post 異步方式登錄-(IBAction)asynchronizationLogin:(UIButton *)btn{ NSMutableURLRequest *request = [self postLoginRequest]; // 注意此處使用了塊代碼!異步請求隊列使用的是操作隊列的主隊列 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if([data length]>0 && connectionError==nil) { NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"異步成功返回的數據%@",string); } else if ([data length] <=0 && connectionError==nil) { NSLog(@"沒有接收到返回數據"); } else { NSLog(@"異步訪問錯誤%@",connectionError.localizedDescription); } }];}
新聞熱點
疑難解答