ios网络NSURLConnection POST

 1 #import "HMViewController.h"
 2 #import "MBProgressHUD+MJ.h"
 3 
 4 @interface HMViewController ()
 5 @property (weak, nonatomic) IBOutlet UITextField *usernameField;
 6 @property (weak, nonatomic) IBOutlet UITextField *pwdField;
 7 - (IBAction)login;
 8 @end
 9 
10 @implementation HMViewController
11 
12 
13 /**
14  *  登录逻辑
15  */
16 - (IBAction)login
17 {
18     // 1.表单验证(输入验证)
19     NSString *username = self.usernameField.text;
20     if (username.length == 0) { // 没有输入用户名
21         [MBProgressHUD showError:@"请输入用户名"];
22         return;
23     }
24     
25     NSString *pwd = self.pwdField.text;
26     if (pwd.length == 0) { // 没有输入密码
27         [MBProgressHUD showError:@"请输入密码"];
28         return;
29     }
30     
31     // 弹框
32     [MBProgressHUD showMessage:@"正在拼命登录中..."];
33     
34     // 2.发送请求给服务器(带上帐号和密码)
35     // POST请求:请求体
36     
37     // 2.1.设置请求路径
38     NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/MJServer/login"];
39     
40     // 2.2.创建请求对象
41     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 默认就是GET请求
42     request.timeoutInterval = 5; // 设置请求超时
43     request.HTTPMethod = @"POST"; // 设置为POST请求
44     
45     // 通过请求头告诉服务器客户端的类型
46     [request setValue:@"ios" forHTTPHeaderField:@"User-Agent"];
47     
48     // 设置请求体
49     NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", username, pwd];
50     request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
51     
52     // 2.3.发送请求
53     NSOperationQueue *queue = [NSOperationQueue mainQueue];
54     [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {  // 当请求结束的时候调用 (拿到了服务器的数据, 请求失败)
55         // 隐藏HUD (刷新UI界面, 一定要放在主线程, 不能放在子线程)
56         [MBProgressHUD hideHUD];
57         
58         /**
59          解析data :
60          {"error":"用户名不存在"}
61          {"error":"密码不正确"}
62          {"success":"登录成功"}
63          */
64         if (data) { // 请求成功
65             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
66             NSString *error = dict[@"error"];
67             if (error) { // 登录失败
68                 [MBProgressHUD showError:error];
69             } else { // 登录成功
70                 NSString *success =  dict[@"success"];
71                 [MBProgressHUD showSuccess:success];
72             }
73         } else { // 请求失败
74             [MBProgressHUD showError:@"网络繁忙, 请稍后再试"];
75         }
76     }];
77 }
78 
79 @end

 

posted @ 2016-01-25 16:45  xiaocaoera  阅读(165)  评论(0编辑  收藏  举报