用NSURLConnection发送POST请求

Posted on 2016-07-19 15:14  柠檬片  阅读(96)  评论(0)    收藏  举报
 1 - (IBAction)btnClick:(id)sender {
 2     
 3     //0.判断
 4     if (self.userName.text.length == 0) {
 5         [SVProgressHUD showErrorWithStatus:self.userName.placeholder maskType:SVProgressHUDMaskTypeBlack];
 6 //        [SVProgressHUD showInfoWithStatus:@"haha"];
 7         
 8         return;
 9     }
10     
11     if (self.pwd.text.length == 0) {
12           [SVProgressHUD showErrorWithStatus:self.pwd.placeholder maskType:SVProgressHUDMaskTypeBlack];
13        
14         return;
15     }
16     
17     //1.确定请求路径
18     NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
19     
20     //2.创建请求对象
21     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
22     
23     //2.1 请求方法
24     request.HTTPMethod = @"POST";
25     
26     NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@",self.userName.text,self.pwd.text];
27     
28     NSLog(@"%@",param);
29     
30     //2.2 设置请求体
31     request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
32     
33     //3.发请求
34     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
35         
36     
37         if (connectionError) {
38             NSLog(@"请求失败");
39         }else
40         {
41 
42             //4.解析数据
43             NSString *res = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
44             
45            [SVProgressHUD showErrorWithStatus:res maskType:SVProgressHUDMaskTypeBlack];
46             
47             NSLog(@"%@---%@",res,[NSThread currentThread]);
48         }
49 
50     }];
51 }
示例