GET:
// // HMViewController.m // 01-NSURLConnection01-GET请求 // // Created by apple on 14-6-26. // Copyright (c) 2014年 heima. All rights reserved. // #import "HMViewController.h" #import "MBProgressHUD+MJ.h" @interface HMViewController () <NSURLConnectionDataDelegate> @property (weak, nonatomic) IBOutlet UITextField *usernameField; @property (weak, nonatomic) IBOutlet UITextField *pwdField; - (IBAction)login; /** * 用来存放服务器返回的所有数据 */ @property (nonatomic, strong) NSMutableData *responseData; @end @implementation HMViewController - (void)viewDidLoad { [super viewDidLoad]; } /** * 登录逻辑 */ - (IBAction)login { // 1.表单验证(输入验证) NSString *username = self.usernameField.text; if (username.length == 0) { // 没有输入用户名 [MBProgressHUD showError:@"请输入用户名"]; return; } NSString *pwd = self.pwdField.text; if (pwd.length == 0) { // 没有输入密码 [MBProgressHUD showError:@"请输入密码"]; return; } // 弹框 [MBProgressHUD showMessage:@"正在拼命登录中..."]; // 2.发送请求给服务器(带上帐号和密码) // GET请求:请求行请求头 // 2.1.设置请求路径 NSString *urlStr = [NSString stringWithFormat:@"http://192.168.1.200:8080/MJServer/login?username=%@&pwd=%@", username, pwd]; // 转码 urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // URL里面不能包含中文 NSURL *url = [NSURL URLWithString:urlStr]; // 2.2.创建请求对象 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求 request.timeoutInterval = 5; // 设置请求超时 // 2.3.发送请求 [self sendAsync:request]; NSLog(@"---------已经发出请求"); } #pragma mark - NSURLConnectionDataDelegate 代理方法 /** * 请求错误(失败)的时候调用(请求超时断网没有网, 一般指客户端错误) */ - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"connection:didFailWithError:"); [MBProgressHUD hideHUD]; [MBProgressHUD showError:@"网络繁忙, 请稍后再试"]; } /** * 当接受到服务器的响应(连通了服务器)就会调用 */ - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSLog(@"connection:didReceiveResponse:"); // 初始化数据 self.responseData = [NSMutableData data]; } /** * 当接受到服务器的数据就会调用(可能会被调用多次, 每次调用只会传递部分数据) */ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { NSLog(@"connection:didReceiveData:"); // 拼接(收集)数据 [self.responseData appendData:data]; } /** * 当服务器的数据接受完毕后就会调用 */ - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"connectionDidFinishLoading:"); // 隐藏HUD [MBProgressHUD hideHUD]; // 解析服务器返回的数据 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil]; NSString *error = dict[@"error"]; if (error) { // 登录失败 [MBProgressHUD showError:error]; } else { // 登录成功 NSString *success = dict[@"success"]; [MBProgressHUD showSuccess:success]; } } /** * 发送异步请求的方式2: start方法, 代理 */ - (void)sendAsync2:(NSURLRequest *)request { NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self]; [conn start]; // 异步执行 } /** * 发送异步请求的方式1: 类方法, block */ - (void)sendAsync:(NSURLRequest *)request { NSOperationQueue *queue = [NSOperationQueue mainQueue]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 当请求结束的时候调用 (拿到了服务器的数据, 请求失败) // 隐藏HUD (刷新UI界面, 一定要放在主线程, 不能放在子线程) [MBProgressHUD hideHUD]; /** 解析data : {"error":"用户名不存在"} {"error":"密码不正确"} {"success":"登录成功"} */ if (data) { // 请求成功 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSString *error = dict[@"error"]; if (error) { // 登录失败 [MBProgressHUD showError:error]; } else { // 登录成功 NSString *success = dict[@"success"]; [MBProgressHUD showSuccess:success]; } } else { // 请求失败 [MBProgressHUD showError:@"网络繁忙, 请稍后再试"]; } }]; }
POST:
// // HMViewController.m // 02-NSURLConnection02-POST请求 // // Created by apple on 14-6-26. // Copyright (c) 2014年 heima. All rights reserved. // #import "HMViewController.h" #import "MBProgressHUD+MJ.h" @interface HMViewController () @property (weak, nonatomic) IBOutlet UITextField *usernameField; @property (weak, nonatomic) IBOutlet UITextField *pwdField; - (IBAction)login; @end @implementation HMViewController /** * 登录逻辑 */ - (IBAction)login { // 1.表单验证(输入验证) NSString *username = self.usernameField.text; if (username.length == 0) { // 没有输入用户名 [MBProgressHUD showError:@"请输入用户名"]; return; } NSString *pwd = self.pwdField.text; if (pwd.length == 0) { // 没有输入密码 [MBProgressHUD showError:@"请输入密码"]; return; } // 弹框 [MBProgressHUD showMessage:@"正在拼命登录中..."]; // 2.发送请求给服务器(带上帐号和密码) // POST请求:请求体 // 2.1.设置请求路径 NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/MJServer/login"]; // 2.2.创建请求对象 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求 request.timeoutInterval = 5; // 设置请求超时 request.HTTPMethod = @"POST"; // 设置为POST请求 // 通过请求头告诉服务器客户端的类型 [request setValue:@"ios" forHTTPHeaderField:@"User-Agent"]; // 设置请求体 NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", username, pwd]; request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding]; // 2.3.发送请求 NSOperationQueue *queue = [NSOperationQueue mainQueue]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 当请求结束的时候调用 (拿到了服务器的数据, 请求失败) // 隐藏HUD (刷新UI界面, 一定要放在主线程, 不能放在子线程) [MBProgressHUD hideHUD]; /** 解析data : {"error":"用户名不存在"} {"error":"密码不正确"} {"success":"登录成功"} */ if (data) { // 请求成功 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; NSString *error = dict[@"error"]; if (error) { // 登录失败 [MBProgressHUD showError:error]; } else { // 登录成功 NSString *success = dict[@"success"]; [MBProgressHUD showSuccess:success]; } } else { // 请求失败 [MBProgressHUD showError:@"网络繁忙, 请稍后再试"]; } }]; } @end