码迷,mamicode.com
首页 > 移动开发 > 详细

IOS-网络请求

时间:2014-07-22 00:09:36      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:des   style   http   color   os   strong   

网络请求包括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-网络请求,布布扣,bubuko.com

IOS-网络请求

标签:des   style   http   color   os   strong   

原文地址:http://blog.csdn.net/qq285016127/article/details/38018087

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!