使用NSURLConnection發送http網絡請求

GET:ios

//
//  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
相關文章
相關標籤/搜索