Post && Get

 

#import "MViewController.h"

 

@interface MViewController ()

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

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

 

@property (weak, nonatomic) IBOutlet UILabel *logonResult;

 

@end

 

@implementation MJViewController

/**

 所有网络请求,统一使用异步请求!

 

 在今后的开发中,如果使用简单的get/head请求,可以用NSURLConnction异步方法

 GET查/POST增/PUT改/DELETE删/HEAD

 

 GET

 1> URL

 2> NSURLRequest

 3> NSURLConnction 异步

 

 POST

 1> URL

 2> NSMutableURLRequest

    .httpMethod = @"POST";

    str 从 firebug直接粘贴,或者自己写 

    变量名1=数值1&变量名2=数值2

 

    .httpData = [str dataUsingEncoding:NSUTF8StringEncoding];

 3> NSURLConnction 异步

 

 */

- (IBAction)userLogon

{

    [self postLogon];

}

 

#pragma mark - POST登录

- (void)postLogon

{

    // 1. URL

    NSURL *url = [NSURL URLWithString:@"http://localhost/login.php"];

    

    // 2. 请求(可以改的请求)

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // ? POST

    // 默认就是GET请求

    request.HTTPMethod = @"POST";

    // ? 数据体

    NSString *str = [NSString stringWithFormat:@"username=%@&password=%@", self.userName.text, self.userPwd.text];

    // 将字符串转换成数据

    request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding];

    

    // 3. 连接,异步

    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        

        if (connectionError == nil) {

            // 网络请求结束之后执行!

            // 将Data转换成字符串

            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

            

            // num = 2

            NSLog(@"%@ %@", str, [NSThread currentThread]);

            

            // 更新界面

            [[NSOperationQueue mainQueue] addOperationWithBlock:^{

                self.logonResult.text = str;

            }];

        }

    }];

    

    // num = 1

    NSLog(@"come here %@", [NSThread currentThread]);

}

 

#pragma mark - GET登录

- (void)getLogon

{

    // 1. URL

    NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login.php?username=%@&password=%@", self.userName.text, self.userPwd.text];

    

    NSURL *url = [NSURL URLWithString:urlStr];

    

    // 2. Request

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    

    // 3. Connection

    // 1> 登录完成之前,不能做后续工作!

    // 2> 登录进行中,可以允许用户干点别的会更好!

    // 3> 让登录操作在其他线程中进行,就不会阻塞主线程的工作

    // 4> 结论:登陆也是异步访问,中间需要阻塞住

    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        

        if (connectionError == nil) {

            // 网络请求结束之后执行!

            // 将Data转换成字符串

            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

            

            // num = 2

            NSLog(@"%@ %@", str, [NSThread currentThread]);

            

            // 更新界面

            [[NSOperationQueue mainQueue] addOperationWithBlock:^{

                self.logonResult.text = @"登录完成";

            }];

        }

    }];

    

    // num = 1

    NSLog(@"come here %@", [NSThread currentThread]);

    

    NSURLResponse *response = nil;

    // 1. &response真的理解了吗?

    // 2. error:为什么是NULL,而不是nil

    // NULL是C语言的 = 0

    // 在C语言中,如果将指针的地址指向0就不会有危险

    

    // nil是OC的,是一个空对象发送消息不会出问题

//    [response MIMEType];

    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL];

}

 

@end

 

//例1

#import "MWebDelegateViewController.h"

#import "NSString+Password.h"

 

@interface MWebDelegateViewController () <NSURLConnectionDataDelegate>

 

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

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

 

@property (weak, nonatomic) IBOutlet UILabel *logonResult;

 

// 从服务器接收到的数据,进行拼接工作

@property (nonatomic, strong) NSMutableData *data;

 

@property (nonatomic, strong) NSString *myPwd;

 

@end

 

@implementation MJWebDelegateViewController

/**

 1. 用户密码明文只能出现在用户登录窗口,不能再其他任何地方出现密码明文

 2. 其他位置,无论是服务器,还是本地,还是传输过程中,统一使用加密后的算法.

 */

 

- (NSString *)myPwd

{

    return [self.userPwd.text myMD5];

}

 

- (IBAction)userLogon

{

    [self getLogon];

}

 

- (void)getLogon

{

    // 1. URL

    NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login.php?username=%@&password=%@", self.userName.text, self.myPwd];

    

    NSLog(@"%@", self.myPwd);

    

    NSURL *url = [NSURL URLWithString:urlStr];

    

    // 2. Request

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    

    // 3. 连接,已经10多岁了

    // 是一个很古老的技术

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

    

    // 开始工作,在很多多线程技术中,start run

    dispatch_async(dispatch_queue_create("demo", DISPATCH_QUEUE_CONCURRENT), ^{

        [connection start];

    });

}

 

#pragma mark - NSURLConnectionDataDelegate代理方法

#pragma mark 接受到响应

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    // 准备工作

    // 按钮点击就会有网络请求,为了避免重复开辟空间

    if (!self.data) {

        self.data = [NSMutableData data];

    } else {

        [self.data setData:nil];

    }

}

 

#pragma mark 接收到数据,如果数据量大,例如视频,会被多次调用

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    // 拼接数据,二进制流的体现位置

    [self.data appendData:data];

}

 

#pragma mark 接收完成,做最终的处理工作

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    // 最终处理

    NSString *str = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];

    

    NSLog(@"%@ %@", str, [NSThread currentThread]);

}

 

#pragma mark 出错处理,网络的出错可能性非常高

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"%@", error.localizedDescription);

}

 

@end

posted @ 2016-03-30 15:20  lance.xiang  阅读(107)  评论(0编辑  收藏  举报