源码0601-01-掌握-NSURLConnection-GET请求
插件:SVProgressHUD
// ViewController.m // 01-掌握-NSURLConnection-GET请求 #import "ViewController.h" #import <SVProgressHUD.h> @interface ViewController () <NSURLConnectionDataDelegate> @property (weak, nonatomic) IBOutlet UITextField *pwdField; @property (weak, nonatomic) IBOutlet UITextField *usernameField; /** 用来存放服务器返回的数据 */ @property (nonatomic, strong) NSMutableData *responseData; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (IBAction)login { // 检测用户名 NSString *username = self.usernameField.text; if (username.length == 0) { [SVProgressHUD showErrorWithStatus:self.usernameField.placeholder]; return; } // 检测密码 NSString *pwd = self.pwdField.text; if (pwd.length == 0) { [SVProgressHUD showErrorWithStatus:self.pwdField.placeholder]; return; } // [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeBlack]; // 显示HUD [SVProgressHUD showWithStatus:@"哥在帮你登录中..." maskType:SVProgressHUDMaskTypeBlack]; // 0.请求路径 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://120.25.226.186:32812/login?username=%@&pwd=%@", username, pwd]]; // 1.创建请求对象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 2.发送请求 [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 3.解析服务器返回的数据(解析成字符串) NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // 4.回到主线程 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ // 隐藏HUD // [SVProgressHUD dismiss]; // 显示一些提示信息 NSUInteger loc = [string rangeOfString:@"\":\""].location + 3; //查字符在字符串中的位置; NSUInteger len = [string rangeOfString:@"\"}"].location - loc; NSString *msg = [string substringWithRange:NSMakeRange(loc, len)];//截取字符串,参数:给一个开始位置,截取的长度; if ([string containsString:@"success"]) { [SVProgressHUD showSuccessWithStatus:msg]; } else { [SVProgressHUD showErrorWithStatus:msg]; } }]; }]; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { /** 发送一个GET请求给服务器 **/ [self delegateAysnc]; } - (void)delegateAysnc { // 0.请求路径 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"]; // 1.创建请求对象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 2.创建连接对象 // [[NSURLConnection alloc] initWithRequest:request delegate:self]; // NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO]; // [conn start]; [NSURLConnection connectionWithRequest:request delegate:self]; // 取消 // [conn cancel]; } #pragma mark - <NSURLConnectionDataDelegate> -- being /** * 接收到服务器的响应 */ - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // 创建data对象 self.responseData = [NSMutableData data]; NSLog(@"didReceiveResponse"); } /** * 接收到服务器的数据(如果数据量比较大,这个方法会被调用多次) */ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // 不断拼接服务器返回的数据 [self.responseData appendData:data]; NSLog(@"didReceiveData -- %zd", data.length); } /** * 服务器的数据成功接收完毕 */ - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"connectionDidFinishLoading"); NSString *string = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding]; NSLog(@"%@", string); self.responseData = nil; } /** * 请求失败(比如请求超时) */ - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"didFailWithError -- %@", error); } #pragma mark - <NSURLConnectionDataDelegate> -- end /** * 发送异步请求 */ - (void)async { // 0.请求路径 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"]; // 1.创建请求对象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 2.发送请求 [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 请求完毕会来到这个block // 3.解析服务器返回的数据(解析成字符串) NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", string); // NSHTTPURLResponse *r = (NSHTTPURLResponse *)response; // // NSLog(@"%zd %@", r.statusCode, r.allHeaderFields); }]; } /** * 发送同步请求 */ - (void)sync { // 0.请求路径 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=345"]; // NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video"]; // 1.创建请求对象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 2.发送请求 // sendSynchronousRequest阻塞式的方法,等待服务器返回数据 NSHTTPURLResponse *response = nil;//服务器返回的信息要存放到这 NSError *error = nil;//接收的错误信息,存放到这 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; // 3.解析服务器返回的数据(解析成字符串) NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@ %@", string, response.allHeaderFields); } @end
02-掌握-NSURLConnection-POST请求
// // ViewController.m // 02-掌握-NSURLConnection-POST请求 #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { // 1.请求路径 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"]; // 2.创建请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 更改请求方法 request.HTTPMethod = @"POST"; // 设置请求体 request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding]; // 设置超时(5秒后超时) request.timeoutInterval = 5; // 设置请求头 // [request setValue:@"iOS 9.0" forHTTPHeaderField:@"User-Agent"]; // 3.发送请求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if (connectionError) { // 比如请求超时 NSLog(@"----请求失败"); } else { NSLog(@"------%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); } }]; } @end
03-掌握-NSURLConnection-中文URL处理
// ViewController.m // 03-掌握-NSURLConnection-中文URL处理 #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self post]; } - (void)post { // 0.请求路径 NSString *urlStr = @"http://120.25.226.186:32812/login2"; NSURL *url = [NSURL URLWithString:urlStr]; // 1.创建请求对象 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; request.HTTPBody = [@"username=小码哥&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding]; // 2.发送请求 [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 3.解析服务器返回的数据(解析成字符串) NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", string); }]; } - (void)get { // 0.请求路径 NSString *urlStr = @"http://120.25.226.186:32812/login2?username=小码哥&pwd=520it"; // 将中文URL进行转码 urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlStr]; // 1.创建请求对象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 2.发送请求 [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 3.解析服务器返回的数据(解析成字符串) NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", string); }]; } @end
本人无商业用途,仅仅是学习做个笔记,特别鸣谢小马哥,学习了IOS,另日语学习内容有需要文本和音频请关注公众号:riyuxuexishuji