IOS开发之2-----网络请求01

来源:互联网 发布:网络印刷平台20强 编辑:程序博客网 时间:2024/06/08 11:36
在网络请求里面常见的几个类
NSURL(地址)
NSRequest[GET]&NSMutableURLRequest[POST](请求)
NSConnection(连接)

实现NSURLConnectionDataDelegate

网络请求的步骤:

1、创建URL连接 NSURL

2、创建网络请求NSRequest

3、创建网络连接NSConnection

4、开始连接

5、处理返回的数据

//

//  ZZBViewController.m

//  09.GetAndPost

//

//  Created by zzb on 14-8-23.

//  Copyright (c) 2014 zzb. All rights reserved.

//


#import "ZZBViewController.h"


@interface ZZBViewController (){

    NSMutableData *_serverData;

}


@end


@implementation ZZBViewController


- (void)viewDidLoad

{

    [super viewDidLoad];

}


- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    

}

//get请求

- (IBAction)getRequest:(UIButton *)sender {

     _serverData = nil;

//    1、先建立URL

    NSString * urlString = [NSString stringWithFormat:@"http://www.baidu.com" ];

    //    NSURL *url = [[NSURL alloc]initWithString:urlString];

    //此方法urlString没有编码,如果出现中文情况,会出现错误,如果有中文,需要对地址字符串进行%UTF8转码,才可以使用!!!记住要加百分号

    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    //2、建立请求

    NSURLRequest * request = [[NSURLRequestalloc]initWithURL:url];

    //3、建立连接,设置代理

    NSURLConnection * connect = [[NSURLConnectionalloc] initWithRequest:requestdelegate:self];

    //4、启动连接

    [connect start];

}

//创建Post请求

//技巧知识点在这一块,如果不希望其它调用者修改里面的请求,最好将它变成不可以修改的对象,这样防止其它用户乱修改造成错误

- (NSURLRequest *)createPostRequest {

    NSString * stringUrl = [[NSStringalloc]initWithFormat:@"http://www.baidu.com"];

    NSURL * url = [[NSURLalloc ]initWithString:stringUrl];

    NSMutableURLRequest *request = [[NSMutableURLRequestalloc]initWithURL:url];

    [request setTimeoutInterval:5.0f];

    [request setHTTPMethod:@"POST"];

    //    NSData * data1 = [@"" dataUsingEncoding:NSUTF8StringEncoding ];//可以这么写

    NSData * data = [[NSDataalloc]init];

    [request setHTTPBody:data];

    return request;

}


//post请求

- (IBAction)postRequest:(UIButton *)sender {

    NSURLRequest *request;

    request = [self createPostRequest];

    NSURLConnection * connnection = [[NSURLConnectionalloc ]initWithRequest:requestdelegate:self];

    [connnection start];

}

/**

 同步请求:其实就是调用NSURLConnection的类方法sendSynchronousRequest方法

 */

- (IBAction)syncRequest:(UIButton *)sender {

    NSURLResponse * response = [[NSURLResponsealloc ]init];

    NSError * error = nil;

    NSData * data  = [NSURLConnectionsendSynchronousRequest:[selfcreatePostRequest] returningResponse:&responseerror:&error];

    if(error!=nil){

        NSLog(@"错误信息%@",error.localizedDescription);

    }else if(data!=nil){

        NSLog(@"服务器返回的数据%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

    }else{

        NSLog(@"服务器没有返回数据");

    }

    

}

//异步请求:其实就是调用NSURLConnectionsendAsynchronousRequest方法

- (IBAction)asynchRequest:(UIButton *)sender {

    [NSURLConnectionsendAsynchronousRequest:[selfcreatePostRequest] queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *response,NSData *data, NSError *error) {

        if(error!=nil){

            NSLog(@"错误信息%@",error.localizedDescription);

        }else if(data!=nil){

            NSLog(@"服务器返回的数据%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

        }else{

            NSLog(@"服务器没有返回数据");

        }

    }];

}

#pragma -mark 代理方法


//服务器有响应

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

    NSLog(@"--didReceiveResponse --%@",response);

}


//    该方法会被调用多次

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

    if (_serverData ==nil) {//懒加载

        _serverData = [[NSMutableData alloc]initWithData:data];

    }else{

        [_serverData appendData:data];

    }

    NSLog(@"---%@",[[NSString alloc]initWithData:_serverData encoding:NSUTF8StringEncoding]);

   

}

//网络加载完毕

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

    //TODO 处理数据

    //假设返回的数据是UTF-8格式的

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

    NSLog(@"---所有的数据结果%@",data);

}

//访问出错,这个方法一般是必须要处理的---出现的情况,一般访问一半的时候,网断了,数据不完整,所以要清空返回的数据

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

    _serverData = nil;

}

//post方法才会执行

-(void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite{


}





@end



0 0