NSURLRequest封装了一次网络请求所需要的数据,主要封装了以下信息:
NSURLRequest与其子类NSMutableURLRequest
NSURLRequest封装一次网络请求的的步骤
//1.创建请求路径NSString *strURL = [NSString stringWithFormat:@"(此处为URL)/login?username=%@&pwd=%@", @"用户名", @"密码"];NSURL *url = [NSURL URLWithString:];//2.根据请求路径封装请求NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest封装一次网络请求的的步骤
//1.创建请求路径NSURL *url = [NSURL URLWithString:@"(此处为URL)/login"];//2.创建请求NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];//3.设置请求方法request.HTTPMethod = @"POST";//4.设置请求参数request.HTTPBody = [@"username="用户名"&pwd="密码" dataUsingEncoding:NSUTF8StringEncoding];//5.设置超时request.timeoutInterval = 5;
NSURLConnection发送请求的步骤
NSURLConnection的代理
NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error/***遇到错误的时候调用,请求终止*/
NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response/***接收到服务器响应的时候调用*response的中包含了服务器的响应信息,比较有价值是此次请求的数据的总长度*/- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data/***接收到服务器的数据的时候调用,若数据较多会多次调用*通常在该方法中对服务器返回的数据进行存储*也可以在该方法中计算下载进度*/- (void)connectionDidFinishLoading:(NSURLConnection *)connection/***数据加载完毕的时候调用*/
NSURLConnectionDownloadDelegate
- (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes/***每次向沙盒中写文件都会调用该方法*/- (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes/***该方法是支持断点下载的核心*/- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *) destinationURL/***由于:下载的文件保存在tmp文件夹中,该文件夹中的数据会被系统定时删除*所以该方法必须实现,用于将改变数据的存储位置*/
NSURLConnection的请求方式
同步请求(线程会被阻塞)
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];/***data:服务器返回的数据,即请求的数据*request:请求请求对象*response:服务器的响应数据*error:错误信息*/
异步请求
//方法一(block)[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { /** *请求完成回调的block,参数的含义与铜鼓请求相同 */}];//方法二(代理)[NSURLConnection connectionWithRequest:request delegate:self]/***自动发送请求*/NSURLConnection *connect = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];/***需要手动发送请求*/
URL中的中文通要进行处理,通常使用UTF-8编码
//进行如下转码[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
新闻热点
疑难解答