UI网络笔记(一):UI网络之Get同步和异步的明文请求

来源:互联网 发布:阿里云有免费空间吗 编辑:程序博客网 时间:2024/05/19 16:48

 一、网络请求相关内容

1、地址(此处常用)

http://10.0.8.8/sns


2、网络交互

同步、异步

get(明文)、post(密文)

网络极简单

有固定格式,我们只需要改几个参数就得了

get同步     get异步

post同步    post异步


3、Get

在开发阶段用get,因为方便调试,get的网络请求可以直接展在浏览器地址栏,回车浏览器就会显示这个请求的返回值

在上线之后,很多会换成post因为更安全


4、网络请求:

用户(客户端):告诉服务器(地址)想要什么(接口),并提供相应的参数(参数)

服务器:根据客户端的要求(接口)和参数(参数),返回相应的数据(返回值)


5、网络请求的字符串组成

地址:http://10.0.8.8/sns

接口:/my/login.php

参数(key&value组成):username=cdd  password=1111

返回值:

地址+接口+?+参数+&+参数

get有?  看见?就是get


二、Get同步请求(以登录界面为例)

2.1、LogInViewController.m

#import "LogInViewController.h"

#import "MainViewController.h"

#import "GetSynClass.h"


@interface LogInViewController ()<UITextFieldDelegate>

@end


@implementation LogInViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    self.view.backgroundColor = [UIColorredColor];   

    [self makeUI];

}

-(void)makeUI//两个textField一个按钮

{

    for(int i =0;i<2;i++)

    {

        UITextField *text = [[UITextFieldalloc]initWithFrame:CGRectMake(0,64+i*40,320, 30)];

        text.delegate = self;

        text.backgroundColor = [UIColoryellowColor];

        [self.viewaddSubview:text];

        text.tag = 5000+i;

        [text release];

    }

    

    UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    btn.frame = CGRectMake(0,144,320, 30);

    [btn setTitle:@"登陆"forState:UIControlStateNormal];

    [btn addTarget:selfaction:@selector(btnDown)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:btn];

}


-(void)btnDown//发起请求,把我们输入的账号密码通过url和接口发给服务器,等待服务器的返回值,成功就去main失败就弹alert

{

    UITextField *count = (UITextField*)[self.viewviewWithTag:5000];

    UITextField *pass = (UITextField*)[self.viewviewWithTag:5001];  

    [count resignFirstResponder];

    [pass resignFirstResponder];  

    //上面是酱油//   

    //下面是请求//

    NSDictionary *dic = [GetSynClassgetSynWithURL:@"http://10.0.8.8/sns"andInterface:@"/my/login.php"andKeyArr:@[@"username",@"password"]andValueArr:@[count.text,pass.text]andTarget:self];   

    if([dic respondsToSelector:@selector(stringWithFormat:)])

    {//封装类出现error的时候,会返回一个字符串,这里排除error的情况

        return;

    }    

    if([dic[@"code"]isEqualToString:@"login_success"])//登陆成功

    {

        //main

        

        MainViewController *main = [[MainViewControlleralloc]init];

        [self.navigationControllerpushViewController:mainanimated:YES];

        [main release];

    }

    else

    {

        //警报

        UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"警报"message:dic[@"message"]delegate:selfcancelButtonTitle:@"好的"otherButtonTitles:nil,nil];

        [alert show];

        [alert release];

        return;

    }

}

- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


2.2、GetSynClass.h——Get同步请求封装类

#import <Foundation/Foundation.h>

@interface GetSynClass : NSObject


+(id)getSynWithURL:(NSString*)url andInterface:(NSString*)interface andKeyArr:(NSArray*)keyArr andValueArr:(NSArray*)valueArr andTarget:(id)targetVC;

//第一个参数是地址,第二个参数是接口,第三个参数是key数组,第四个参数是value数组,第五个参数是调用的VC


@end


2.3、GetSynClass.m——Get同步请求封装类


#import "GetSynClass.h"

#import <UIKit/UIKit.h>


@implementation GetSynClass


+(id)getSynWithURL:(NSString *)url andInterface:(NSString *)interface andKeyArr:(NSArray *)keyArr andValueArr:(NSArray *)valueArr andTarget:(id)targetVC

{

    //4、做一个可变字符串

    NSMutableString *reqStr = [NSMutableStringstringWithCapacity:0];    

    //5、把urlinterface拼进reqStr

    [reqStr appendString:url];

    [reqStr appendString:interface];   

    //6get请求,在interface后面拼上?(问号)

    [reqStr appendString:@"?"];  

    //7、用循环的方式把参数拼进reqStr

    for(int i =0;i<keyArr.count;i++)

    {

        [reqStr appendFormat:@"%@=%@",keyArr[i],valueArr[i]];//keyvalue中间用=连接       

        //如果不是最后一拼,需要在后面加上&,相邻两个参数之间用&分隔

        if(i<keyArr.count-1)

        {

            [reqStr appendString:@"&"];

        }

    }   

    NSLog(@"%@",reqStr);//把字符串粘进浏览器地址栏检验你的网络请求   

    //8、准备请求体

    NSMutableURLRequest *req = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:reqStr]cachePolicy:NSURLRequestReturnCacheDataElseLoadtimeoutInterval:10];

    //第一个参数是请求内容的URL格式(把拼好的字符串转为NSURL写在这儿)

    //第二个参数是缓存机制(我要不要读缓存,我要不要只读缓存,我要不要不读缓存)

    //第三个参数是超时时间(写个秒数,超过这个秒数,就直接停止请求)

    

    //9、准备error

    NSError *error = nil;    

    //10、发起同步请求,用一个NSData来接收同步请求的返回值

    NSData *backData = [NSURLConnectionsendSynchronousRequest:reqreturningResponse:nilerror:&error];

    if(error)//请求判断

    {

        NSLog(@"%@",error);

        UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"错误"message:@"错啦" delegate:targetVCcancelButtonTitle:@"ok"otherButtonTitles:nil,nil];

        [alert show];

        [alert release];

        return @"error";

    }else{//没出错,可以正常解析

        id dic = [NSJSONSerializationJSONObjectWithData:backDataoptions:NSJSONReadingMutableLeaveserror:&error];

        if(error)//解析判断

        {

            NSLog(@"%@",error);

            UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"警报"message:@"您的网络不够流畅,请换一个位置使用本应用" delegate:targetVC cancelButtonTitle:@"好的" otherButtonTitles:nil,nil];

            [alert show];

            [alert release];

            return @"error1";

        }

        else

        {//解析成功

            return dic;

        }

    }

}

@end


三、Get异步请求(以登录界面为例)

3.1、LogInViewController.m

#import "LogInViewController.h"

#import "MainViewController.h"

#import "GetAsynClass.h"

#import "MBProgressHUD.h"//网络请求小圈圈


@interface LogInViewController ()<UITextFieldDelegate,NSURLConnectionDataDelegate>

@property(nonatomic,retain)NSMutableData *data;//用来一点一点接data

@end


@implementation LogInViewController

-(void)dealloc

{

    self.data =nil;

    [super dealloc];

}

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];

    if(self)

    {

        self.data = [NSMutableDatadataWithCapacity:0];

    }

    return self;

}


- (void)viewDidLoad {

    [super viewDidLoad];   

    self.view.backgroundColor = [UIColorredColor];    

    [self makeUI];

}


-(void)makeUI

{

    for(int i =0;i<2;i++)

    {

        UITextField *text = [[UITextFieldalloc]initWithFrame:CGRectMake(0,64+i*40,320, 30)];

        text.delegate = self;

        text.backgroundColor = [UIColoryellowColor];

        text.tag = 5000+i;

        [self.viewaddSubview:text];

        [text release];

    }

    UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    btn.frame = CGRectMake(0,144,320, 30);

    btn.backgroundColor = [UIColorgreenColor];

    [btn setTitle:@"sign"forState:UIControlStateNormal];

    [btn addTarget:selfaction:@selector(btnDown)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:btn];

}


-(void)btnDown

{

    //每次都要清data

    [self.dataresetBytesInRange:NSMakeRange(0,self.data.length)];

    [self.datasetLength:0];

    

    UITextField *count = (UITextField*)[self.viewviewWithTag:5000];

    UITextField *pass = (UITextField*)[self.viewviewWithTag:5001];

    [count resignFirstResponder];

    [pass resignFirstResponder];   

    //上面是酱油    

    //圈圈出现

    MBProgressHUD *mb = [[MBProgressHUDalloc]initWithView:self.view];

    mb.labelText =@"正在努力加载中...";//圈圈上的字

    mb.dimBackground =YES;//外边轮廓是否半透明

    [self.viewaddSubview:mb];

    [mb show:YES];//显示

    [mb release];

    mb.tag = 12345

    //下面是请求

    [GetAsynClassgetAsynWithURL:@"http://10.0.8.8/sns"andInterface:@"/my/login.php"andKeyArr:@[@"username",@"password"]andValueArr:@[count.text,pass.text]andDelegateTarget:self];

}


#pragma mark 异步网络请求代理

//请求失败的时候调用,或者超时的时候调用

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

{

    MBProgressHUD *mb = (MBProgressHUD*)[self.viewviewWithTag:12345];

    [mb removeFromSuperview];

    mb = nil;    

    NSLog(@"%@",error);    

    UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"警报"message:@"您的网络不好,换地儿please" delegate:selfcancelButtonTitle:@"好的"otherButtonTitles:nil,nil];

    [alert show];

    [alert release];

    

}

//获得返回值头,包括比如返回值的总大小之类的数据

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

{

    //记录一些基本情况,以后用

}

//开始一点一点接受返回值数据,这个方法会被多次调用,直到这次网络请求的数据全部接受完毕

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

{

    [self.dataappendData:data];//一点一点接

}


//接完了以后

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    MBProgressHUD *mb = (MBProgressHUD*)[self.viewviewWithTag:12345];

    [mb removeFromSuperview];

    mb = nil;

    

    NSError *error = nil;

    //开始解析self.data

    NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:self.dataoptions:NSJSONReadingMutableLeaveserror:&error];

    if(error)

    {//解析失败,弹出警报,return

        UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"警报"message:@"您的网络有故障,太慢,换个地儿吧,这么好的应用别浪费" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil,nil];

        [alert show];

        [alert release];

        return;

    }

    else

    {//解析成功,判断内容,是不是login_success

        if([dic[@"code"]isEqualToString:@"login_success"])

        {//登陆成功,push

            

            //id

            NSUserDefaults *user = [NSUserDefaultsstandardUserDefaults];

            [user setObject:dic[@"m_auth"]forKey:@"myAuth"];

            [user setObject:dic[@"uid"]forKey:@"myId"];

            [user synchronize];//同步存

            

            MainViewController *main = [[MainViewControlleralloc]init];

            [self.navigationControllerpushViewController:mainanimated:YES];

            [main release];

        }

        else

        {//登录失败,alert,应该展示给用户返回值里类似message的内容

            UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"警告"message:dic[@"message"]delegate:selfcancelButtonTitle:@"好吧"otherButtonTitles:nil,nil];

            [alert show];

            [alert release];

            return;

        }

    }

}


3.2、GetAsynClass.h——Get异步请求封装类

#import <Foundation/Foundation.h>

@interface GetAsynClass : NSObject

+(void)getAsynWithURL:(NSString*)url andInterface:(NSString*)interface andKeyArr:(NSArray*)keyArr andValueArr:(NSArray*)valueArr andDelegateTarget:(id)targetVC;

@end


3.3、GetAsynClass.m——Get异步请求封装类

#import "GetAsynClass.h"


@implementation GetAsynClass


+(void)getAsynWithURL:(NSString *)url andInterface:(NSString *)interface andKeyArr:(NSArray *)keyArr andValueArr:(NSArray *)valueArr andDelegateTarget:(id)targetVC

{

    //4、准备可变字符串

    NSMutableString *reqStr = [NSMutableStringstringWithCapacity:0];

    //5、拼urlinterface

    [reqStr appendString:url];

    [reqStr appendString:interface];

    [reqStr appendString:@"?"];//get加?

    //6、循环拼keyvalue

    for(int i =0;i<keyArr.count;i++)

    {

        [reqStr appendFormat:@"%@=%@",keyArr[i],valueArr[i]];

        if(i<keyArr.count-1)

        {

            [reqStr appendString:@"&"];

        }

    }

    NSLog(@"%@",reqStr);//粘到浏览器里检验

    

    //7、准备请求体

    NSMutableURLRequest *req = [NSMutableURLRequestrequestWithURL:[NSURLURLWithString:reqStr]cachePolicy:NSURLRequestReloadIgnoringCacheDatatimeoutInterval:10];

    

    //8、准备异步请求

    NSURLConnection *connection = [NSURLConnectionconnectionWithRequest:reqdelegate:targetVC];

    

    //9、开始异步请求

    [connection start];

}

@end


四、主界面接收数据(老师的上课程序,没有写完整)

#import "MainViewController.h"

#import "GetAsynClass.h"

#import "MBProgressHUD.h"

#import "NSString+URLEncoding.h"//去非法字符


@interface MainViewController ()<NSURLConnectionDataDelegate>

@property(nonatomic,retain)NSMutableData *data;//接受数据

@property(nonatomic,retain)NSMutableArray *dataArr;//数据源

@end


@implementation MainViewController

-(void)dealloc

{

    self.data =nil;

    self.dataArr =nil;

    [super dealloc];

}


-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];

    if(self)

    {

        self.dataArr = [NSMutableArrayarrayWithCapacity:0];

        self.data = [NSMutableDatadataWithCapacity:0];

    }

    return self;

}


- (void)viewDidLoad {

    [superviewDidLoad];

    

    self.view.backgroundColor = [UIColorgreenColor];

    

    [self makeUI];

    

    [self loadData];

    // Do any additional setup after loading the view.

}

//做一个table

-(void)makeUI

{

    

}

//请求数据(发起网络请求)

-(void)loadData

{

    NSUserDefaults *user = [NSUserDefaultsstandardUserDefaults];

    NSString *uid = [user objectForKey:@"myId"];

    NSString *auth = [user objectForKey:@"myAuth"];

    

    NSString *finalAuth = [auth urlEncodeString];

    NSLog(@"%@",finalAuth);

    NSLog(@"%@",auth);

    

    [GetAsynClassgetAsynWithURL:@"http://10.0.8.8/sns"andInterface:@"/my/profile.php"andKeyArr:@[@"uid",@"m_auth"]andValueArr:@[uid,finalAuth]andDelegateTarget:self];

}

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

{

    [self.dataappendData:data];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    //解析数据,刷新table

    NSDictionary *dic = [NSJSONSerializationJSONObjectWithData:self.dataoptions:NSJSONReadingMutableLeaveserror:nil];

    NSLog(@"%@",dic);

}


0 0
原创粉丝点击