NSURLConnection和NSMutableURLRequest 实现同步、异步请求 和 NSInputStream和NSMutableURLRequest-实现保存文件到服务器

http://blog.sina.com.cn/s/blog_7b9d64af01019p6q.html

一、同步请求-GET方式


// 要请求的地址

    NSString *urlString=@"地址,我就只有保密了!你懂的";

// 将地址编码

    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    // 实例化NSMutableURLRequest,并进行参数配置

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

[request setURL:[NSURL URLWithString: urlString]];

[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];

[request setTimeoutInterval: 60];

[request setHTTPShouldHandleCookies:FALSE];

[request setHTTPMethod:@"GET"];


    // Response对象,用来得到返回后的数据,比如,用statusCode==200 来判断返回正常

    NSHTTPURLResponse *response;

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request

                                               returningResponse:&response error:nil];


    // 处理返回的数据

    NSString *strReturn = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"%@",strReturn);

    NSLog(@"%d",[response statusCode]);

    // 对象还是要释放的

    [request release];

    [strReturn release];


关于,同步GET请求,也没有什么好说的。我都做了备注!

二、异步请求-GET方式

这种,方式请求就有点麻烦了!因为是异步的嘛。
根据以下步骤:
1.在*.h文件中,实现NSURLConnectionDelegate协议。
例如:

@interface MoreViewController : UIViewController<</span>NSURLConnectionDelegate>


2.在*.m文件中,进行异步请求和实现协议方法。

异步请求:

NSString *urlString=@"地址,我就只有保密了!你懂的";

urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

[request setURL:[NSURL URLWithString: urlString]];

[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];

[request setTimeoutInterval: 60];

[request setHTTPShouldHandleCookies:FALSE];

[request setHTTPMethod:@"GET"];

    // NSURLConnection* aSynConnection 可以申明为全局变量.

    // 在协议方法中,通过判断aSynConnection,来区分,是哪一个异步请求的返回数据。

    aSynConnection = [[NSURLConnection alloc] initWithRequest:requestdelegate:self];


协议方法:

 

#pragma mark- NSURLConnectionDelegate 协议方法


 

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

    NSLog(@"请求成功!");

    returnInfoData=[[NSMutableData alloc]init];

}


 

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

    [returnInfoData appendData:data];

}


 

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

    NSLog(@"didFailWithError");

}


 

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

    if( [connection isEqualaSynConnection])

    {

        NSString *asyReturn = [[NSString alloc] initWithData:returnInfoDataencoding:NSUTF8StringEncoding];

        NSLog(@"%@",asyReturn);

        [returnInfoData release];

        returnInfoData = nil;

        [asyReturn release];

    }

}


关于,POST请求,因为没有地址让我测试,就暂时,先不贴了!
就是要设置一些POST的相关参数:

    [request setHTTPMethod:@"POST"];

    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    [request setValue:@"application/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];

    [request setHTTPBody:postData];


等有机会,让我测试通了,在贴!

但是,我发现,这样的事情:
上边提及的几个协议方法,是过期了的。所以,虽然能用,但是,总感觉不好。应该有替代的相关方法吧。

于是,继续追寻。终于找到了!

原来,苹果官方,将NSURLConnectionDelegate协议废除(虽然还能用),并使用NSURLConnectionDataDelegate协议来代替。并且重写了相关的一些方法。分别看一下,这两个协议就清楚了。

@protocol NSURLConnectionDelegate <<span style="color: #743fa4">NSObject>

@protocol NSURLConnectionDataDelegate <<span style="color: #743fa4">NSURLConnectionDelegate>


做个标记,以待来着!

希望对您有所帮助!

http://blog.sina.com.cn/s/blog_7b9d64af01019qdr.html

场景:

有时候,我们需要保存iPhone本地的资源(图片为例)到服务器的相应路径。那么就需要将本地图片上传到服务器。这样,可以用NSInputStream + NSURLConnection +NSMutableURLRequest来实现图片上传。

1.准备工作,将需要的类进行声明定义。
*.h 文件

NSURLConnection* _aSynConnection;

NSInputStream *_inputStreamForFile;

NSString *_localFilePath;


@property (nonatomic,retain) NSURLConnection* aSynConnection;

@property (nonatomic,retainNSInputStream *inputStreamForFile;

@property (nonatomic,retain) NSString *localFilePath;


*.m 文件

@synthesize inputStreamForFile=_inputStreamForFile;

@synthesize localFilePath=_localFilePath;

@synthesize aSynConnection=_aSynConnection;


2.进行请求

关于,使用进行请求的相关知识,可以看我另一篇博客,在这里就不再赘述了。


// 我将其写入按钮事件中

- (void)btnClickAction:(id)sender{

    NSLog(@"--------btnClickAction--------");

    

   


    // 初始化目标地址的URL(发送到哪里)

    NSURL *serverURL;

    NSString *strURL=@"http://www.xxx.com/fileName.png";// 这里用图片为例

strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    serverURL=[NSURL URLWithString:strURL];

    

    // 初始化本地文件路径,并与NSInputStream链接

    self.localFilePath=@"本地的图片路径";

    self.inputStreamForFile = [NSInputStream inputStreamWithFileAtPath:self.localFilePath];

    

    // 上传大小

    NSNumber *contentLength;

    contentLength = (NSNumber *) [[[NSFileManager defaultManager]attributesOfItemAtPath:self.localFilePath error:NULL] objectForKey:NSFileSize];

    

   

    NSMutableURLRequest *request;

    request = [NSMutableURLRequest requestWithURL:serverURL];

    [request setHTTPMethod:@"PUT"];

    [request setHTTPBodyStream:self.inputStreamForFile];

    [request setValue:@"image/png" forHTTPHeaderField:@"Content-Type"];

    [request setValue:[contentLength description] forHTTPHeaderField:@"Content-Length"];

    

    // 请求

    self.aSynConnection = [NSURLConnection connectionWithRequest:requestdelegate:self];

    


}


3.接受回调函数的状态,判断是否上传成功。


// 收到响应时,会触发

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

    NSLog(@"请求成功!");

    returnInfoData=[[NSMutableData alloc]init];

    totalSize= [aResponse expectedContentLength];

    

    NSHTTPURLResponse * httpResponse;

    httpResponse = (NSHTTPURLResponse *)aResponse;

    if ((httpResponse.statusCode / 100) != 2) {

        NSLog(@"保存失败");

    } else {

        NSLog(@"保存成功");

    }

}



希望对你有所帮助!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值