網絡請求包括GET.POST兩種方式,其步驟為:1>獲取URL。 2>獲取請求。 3>創建鏈接。 4>返回數據(代理)。
1>獲取URL。
NSString *urlStr=@"http://api.zbw.vc/api/vip/GetPhonePadTagMsg"; //當參數為中文時,用UTF8編碼 //urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url=[NSURL URLWithString:urlStr];
2>獲取請求。
NSURLRequest *request=[NSURLRequest requestWithURL:url];
默認get方法的參數只需要URL拼接。
當創建post方法的時候,對request進行如下操作
NSString *dataStr=[NSString stringWithFormat:@"UserName=%@&LoginPwd=%@",self.QQField.text,self.pwdField.text]; NSData *data=[dataStr dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody:data]; [request setHTTPMethod:@"POST"]; [request setTimeoutInterval:5.0];
3>創建鏈接。
此時,創建的 代理為本類,所以該類必須繼承協議
NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
4>返回數據(代理)。實現代理必須實現如下方法
//網絡返回數據開始 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response //重復調用,返回數據處理 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data //返回數據結束 -(void)connectionDidFinishLoading:(NSURLConnection *)connection //發生錯誤處理方法 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
1.同步>>
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&error];
2.異步>>[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(block)];
具體代碼如下:
#import "CSZViewController.h" @interface CSZViewController () @property (nonatomic,strong) NSMutableData *mutableData; @end @implementation CSZViewController - (void)viewDidLoad { [super viewDidLoad]; } - (NSURLRequest *)getRequest { NSString *urlStr=@"http://api.zbw.vc/api/vip/GetPhonePadTagMsg"; //當參數為中文時,用UTF8編碼 //urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url=[NSURL URLWithString:urlStr]; NSURLRequest *request=[NSURLRequest requestWithURL:url]; return request; } - (IBAction)getLogin { NSURLRequest *request = [self getRequest]; NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self]; [conn start]; } - (NSMutableURLRequest *)getAsyncRequest { NSString *urlStr=@"http://api.zbw.vc/api/Vip/PostUserInfo"; NSURL *url=[NSURL URLWithString:urlStr]; NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url]; NSString *dataStr=[NSString stringWithFormat:@"UserName=%@&LoginPwd=%@",self.QQField.text,self.pwdField.text]; NSData *data=[dataStr dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody:data]; [request setHTTPMethod:@"POST"]; [request setTimeoutInterval:5.0]; return request; } - (IBAction)postLogin { [UIApplication sharedApplication].networkActivityIndicatorVisible=YES; NSMutableURLRequest *request = [self getAsyncRequest]; NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self]; [conn start]; } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"%@",@"網絡返回數據開始"); } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { if (_mutableData==nil) { _mutableData=[NSMutableData data]; } [_mutableData appendData:data]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { _mutableData=nil; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *str=[[NSString alloc] initWithData:_mutableData encoding:NSUTF8StringEncoding]; NSLog(@"%@",str); if (_mutableData!=nil) { _mutableData=nil; } [UIApplication sharedApplication].networkActivityIndicatorVisible=NO; } - (IBAction)clickSync { NSURLRequest *request = [self getRequest]; NSURLResponse *resp=nil; NSError *error=nil; NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&error]; if (error!=nil) { NSLog(@"%@",error.localizedDescription); return; } if (data!=nil) { //解碼 NSString *respStr=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",respStr); } else { NSLog(@"獲取不到網絡數據"); } } - (IBAction)clickAsync { NSURLRequest *request = [self getAsyncRequest]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if (connectionError!=nil) { NSLog(@"%@",connectionError.localizedDescription); }else if (response!=nil) { //解碼 NSString *res=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",res); }else{ NSLog(@"獲取不到網絡數據"); } }]; } @end