iOS 網路編程 GET 與 POST

來源:互聯網
上載者:User

標籤:

//

//  ViewController.m

//  NetWork 1

//

//  Created by Lenny  on 3/21/15.

//  Copyright (c) 2015 Lenny. All rights reserved.

//

 

#import "ViewController.h"

#import "MBProgressHUD+MJ.h"

 

@interface ViewController ()<</span>NSURLConnectionDataDelegate>

@property (weak, nonatomic) IBOutlet UITextField *nameField;

@property (weak, nonatomic) IBOutlet UITextField *pwdField;

- (IBAction)loginBtnClick;

 

@property(nonatomic,strong)NSMutableData * responseData;

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

}

 

 

- (IBAction)loginBtnClick {

    NSString *username  = self.nameField.text;

    NSString * pwd = self.pwdField.text;

    if (username.length == 0) {//沒有使用者名稱的輸入

        [MBProgressHUD showError:@"enter the user name"];

        return;

    }

    if (pwd.length == 0) {

        [MBProgressHUD showError:@"enter the pwd"];

        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 = 10;//佈建要求逾時

//    發送請求 注意這裡的請求是非同步請求

    [self sendAsync:request];

    NSLog(@"請求已經發出");

    

}

 

 

-(void)sendAsync:(NSURLRequest *)request

{

    //    這裡隊列使用的是主線程

    NSOperationQueue * queue = [NSOperationQueue mainQueue];

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {//當請求結束的時候調用(拿到了伺服器的資料,請求失敗)

        //        隱藏HUD(重新整理UI介面,一定要放在主線程中使用,不能放在子線程中使用)

        [MBProgressHUD hideHUD];

        

        if (data) {//請求成功

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

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

            if (error) {//表示登入失敗

                [MBProgressHUD showError:error];

            }else

            {

                [MBProgressHUD showSuccess:dict[@"success"]];

            }

        }else{

            [MBProgressHUD showError:@"網路繁忙,請稍後重試...."];

        }

        

        

        

    }];

}

 

-(void)sendAsync2:(NSURLRequest *)request

{

    NSURLConnection * conn = [NSURLConnection connectionWithRequest:request delegate:self];

    [conn start];//非同步執行開始

    

}

 

#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];

    }

    

}

@end

     

//

//  ViewController.m

//  POST

//

//  Created by Lenny  on 3/21/15.

//  Copyright (c) 2015 Lenny. All rights reserved.

//

 

#import "ViewController.h"

#import "MBProgressHUD+MJ.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextField *nameField;

@property (weak, nonatomic) IBOutlet UITextField *pwdField;

- (IBAction)loginBtnClick;

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}

 

 

- (IBAction)loginBtnClick {

    NSString *username  = self.nameField.text;

    NSString * pwd = self.pwdField.text;

    if (username.length == 0) {//沒有使用者名稱的輸入

        [MBProgressHUD showError:@"enter the user name"];

        return;

    }

    if (pwd.length == 0) {

        [MBProgressHUD showError:@"enter the pwd"];

        return;

    }

    //    彈框正在登入中....

    [MBProgressHUD showMessage:@"正在拚命的為您載入中...."];

    //    2.發送請求給伺服器(賬戶名稱和使用者密碼)

    //    GET請求:請求行\要求標頭

    //    2.1佈建要求路徑

    NSString * urlStr = [NSString stringWithFormat:@"http://192.168.1.200:8080/LKServer/login"];

    //    進行轉碼的操作 如果其中有中文字元 那麼將其轉走

    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    //    URL裡面不可以含有中文

    NSURL * url = [NSURL URLWithString:urlStr];

    //    2.2建立請求對象

    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];//預設就是GET請求的方式

    request.HTTPMethod = @"POST";//設定成為POST請求的方式

    

//    通過要求標頭告訴伺服器 用戶端的類型

    [request setValue:@"iOS" forKey:@"User-Agent"];

//    佈建要求體

    NSString * param = [NSString stringWithFormat:@"username=%@&pwd=%@", username, pwd];

    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];

    request.timeoutInterval = 5;//佈建要求逾時

    //    發送請求 注意這裡的請求是非同步請求

//    發送資料請求

    NSOperationQueue * queue = [NSOperationQueue mainQueue];

    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {// 當請求結束的時候調用 (拿到了伺服器的資料, 請求失敗)

        // 隱藏HUD (重新整理UI介面, 一定要放在主線程, 不能放在子線程)

        [MBProgressHUD hideHUD];

        if (data) {//請求成功

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

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

            if (error) {//登入失敗

                [MBProgressHUD showError:error];

            }else

            {

                [MBProgressHUD showSuccess:dict[@"success"]];

            }

        }else{

            [MBProgressHUD showError:@"網路繁忙,請稍後再試"];

        }

 

        

    }];

    

}

 

@end

 

iOS 網路編程 GET 與 POST

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.