IOS-网络请求

网络请求包括GET.POST两种方式,其步骤为:1>获取URL。 2>获取请求。 3>创建链接。 4>返回数据(代理)。

1>获取URL。 

NSString *urlStr=@"http://api.zbw.vc/api/vip/GetPhonePadTagMsg";
//当参数为中文时,用UTF8编码
//urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlStr];

2>获取请求。 

NSURLRequest *request=[NSURLRequest requestWithURL:url];

默认get方法的参数只需要URL拼接。

当创建post方法的时候,对request进行如下操作

<span style="font-size:18px;">NSString *dataStr=[NSString stringWithFormat:@"UserName=%@&LoginPwd=%@",self.QQField.text,self.pwdField.text];
NSData *data=[dataStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
[request setHTTPMethod:@"POST"];
[request setTimeoutInterval:5.0];</span>

3>创建链接。 

此时,创建的 代理为本类,所以该类必须继承协议<NSURLConnectionDataDelegate>

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

4>返回数据(代理)。实现代理必须实现如下方法

<span style="font-size:18px;">//网络返回数据开始
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
//重复调用,返回数据处理
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
//返回数据结束
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
//发生错误处理方法
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error</span>


IOS提供另一种方法实现数据回传

1.同步>>

NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&error];

2.异步>>

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(block)];


具体代码如下:

<span style="color:#333333;">#import "CSZViewController.h"

@interface CSZViewController ()

@property (nonatomic,strong) NSMutableData *mutableData;

@end

@implementation CSZViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

}


- (NSURLRequest *)getRequest {
    NSString *urlStr=@"http://api.zbw.vc/api/vip/GetPhonePadTagMsg";
    //当参数为中文时,用UTF8编码
    //urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:urlStr];
    
    NSURLRequest *request=[NSURLRequest requestWithURL:url];
    return request;
}

- (IBAction)getLogin {
    
    NSURLRequest *request = [self getRequest];
    NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
    [conn start];
}

- (NSMutableURLRequest *)getAsyncRequest {
    NSString *urlStr=@"http://api.zbw.vc/api/Vip/PostUserInfo";
    NSURL *url=[NSURL URLWithString:urlStr];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    
    NSString *dataStr=[NSString stringWithFormat:@"UserName=%@&LoginPwd=%@",self.QQField.text,self.pwdField.text];
    
    NSData *data=[dataStr dataUsingEncoding:NSUTF8StringEncoding];
    
    [request setHTTPBody:data];
    [request setHTTPMethod:@"POST"];
    [request setTimeoutInterval:5.0];
    return request;
}

- (IBAction)postLogin {
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
    
    NSMutableURLRequest *request = [self getAsyncRequest];
    NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
    [conn start];
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%@",@"网络返回数据开始");
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (_mutableData==nil) {
        _mutableData=[NSMutableData data];
    }
    [_mutableData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    _mutableData=nil;
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *str=[[NSString alloc] initWithData:_mutableData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
    
    if (_mutableData!=nil) {
        _mutableData=nil;
    }
    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
}

- (IBAction)clickSync {
    NSURLRequest *request = [self getRequest];
    NSURLResponse *resp=nil;
    NSError *error=nil;
    NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&error];
    if (error!=nil) {
        NSLog(@"%@",error.localizedDescription);
        return;
    }
    
    if (data!=nil) {
        //解码
        NSString *respStr=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",respStr);
    }
    else
    {
        NSLog(@"获取不到网络数据");
    }
    
}

- (IBAction)clickAsync {
    NSURLRequest *request = [self getAsyncRequest];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError!=nil) {
            NSLog(@"%@",connectionError.localizedDescription);
        }else if (response!=nil) {
            //解码
            NSString *res=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",res);
        }else{
            NSLog(@"获取不到网络数据");
        }
    }];
    
    
}

@end</span>

IOS-网络请求,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。