HTTP请求的简单使用

//模拟登陆

- (IBAction)login {

    // 1.用户名

    NSString *usernameText = self.username.text;

    if (usernameText.length == 0) {

        [MBProgressHUD showError:@"请输入用户名"];

        return;

    }

    // 2.密码

    NSString *pwdText = self.pwd.text;

    if (pwdText.length == 0) {

        [MBProgressHUD showError:@"请输入密码"];

        return;

    }

    

    // 增加蒙板

    [MBProgressHUD showMessage:@"正在拼命登录中...."];

    

    // 3.发送用户名和密码给服务器(走HTTP协议)

    // 创建一个URL : 请求路径

    NSURL *url = [NSURL URLWithString:@"http://117.169.34.234:8090/login/LoginAction.aspx"];

    

    // 创建一个请求

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    

    // 5秒后算请求超时(默认60s超时)

    request.timeoutInterval = 15;

    

    request.HTTPMethod = @"POST";

    // 设置请求体

    NSString *param = [NSString stringWithFormat:@"logincode=%@&password=%@", usernameText, pwdText];

    // NSString --> NSData

    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];

    

    // 发送一个同步请求(在主线程发送请求)

    // queue :存放completionHandler这个任务

    NSOperationQueue *queue = [NSOperationQueue mainQueue];

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:

     ^(NSURLResponse *response, NSData *data, NSError *connectionError) {

         [MBProgressHUD hideHUD];

         

         // 这个block会在请求完毕的时候自动调用

         if (connectionError || data == nil) { // 一般请求超时就会来到这

             [MBProgressHUD showError:@"请求失败"];

             return;

         }

         // 解析服务器返回的JSON数据

         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

         NSString *error = dict[@"error"];

         if (error) {

             NSLog(@"fail");

         } else {

             NSLog(@"success");

             NSLog(@"%@",dict);

         }

     }];

}

posted @ 2015-11-19 14:02  灿锋的博客  阅读(106)  评论(0)    收藏  举报