实现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 = [[NSURLRequest alloc]initWithURL:url];
//3、建立连接,设置代理
NSURLConnection * connect = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//4、启动连接
[connect start];
}
//创建Post请求
//技巧知识点:在这一块,如果不希望其它调用者修改里面的请求,最好将它变成不可以修改的对象,这样防止其它用户乱修改造成错误
- (NSURLRequest *)createPostRequest {
NSString * stringUrl = [[NSString alloc]initWithFormat:@"http://www.baidu.com"];
NSURL * url = [[NSURL alloc ]initWithString:stringUrl];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
[request setTimeoutInterval:5.0f];
[request setHTTPMethod:@"POST"];
// NSData * data1 = [@"" dataUsingEncoding:NSUTF8StringEncoding ];//可以这么写
NSData * data = [[NSData alloc]init];
[request setHTTPBody:data];
return request;
}
//post请求
- (IBAction)postRequest:(UIButton *)sender {
NSURLRequest *request;
request = [self createPostRequest];
NSURLConnection * connnection = [[NSURLConnection alloc ]initWithRequest:request delegate:self];
[connnection start];
}
/**
同步请求:其实就是调用NSURLConnection的类方法sendSynchronousRequest方法
*/
- (IBAction)syncRequest:(UIButton *)sender {
NSURLResponse * response = [[NSURLResponse alloc ]init];
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:[self createPostRequest] returningResponse:&response error:&error];
if(error!=nil){
NSLog(@"错误信息%@",error.localizedDescription);
}else if(data!=nil){
NSLog(@"服务器返回的数据%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}else{
NSLog(@"服务器没有返回数据");
}
}
//异步请求:其实就是调用NSURLConnection的sendAsynchronousRequest方法
- (IBAction)asynchRequest:(UIButton *)sender {
[NSURLConnection sendAsynchronousRequest:[self createPostRequest] queue:[NSOperationQueue mainQueue] 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