iOS开发网络篇—NSURLConnection基本使用
最新博文发布地址 花田半亩http://wendingding.com/
iOS开发网络篇—NSURLConnection基本使用
一、NSURLConnection的常用类
(1)NSURL:请求地址
(2)NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个NSURL对象,请求方法、请求头、请求体....
(3)NSMutableURLRequest:NSURLRequest的子类
(4)NSURLConnection:负责发送请求,建立客户端和服务器的连接。发送NSURLRequest的数据给服务器,并收集来自服务器的响应数据
使用NSURLConnection发送请求的步骤很简单
(1)创建一个NSURL对象,设置请求路径(设置请求路径)
(2)传入NSURL创建一个NSURLRequest对象,设置请求头和请求体(创建请求对象)
(3)使用NSURLConnection发送NSURLRequest(发送请求)

2.代码示例
(1)发送请求的三个步骤:
//
// YYViewController.m
// 01-NSURLConnection的使用(GET)
//
// Created by apple on 14-6-28.
// Copyright (c) 2014年 itcase. All rights reserved.
// #import "YYViewController.h"
#import "MBProgressHUD+MJ.h" @interface YYViewController ()
@property (weak, nonatomic) IBOutlet UITextField *username;
@property (weak, nonatomic) IBOutlet UITextField *pwd;
- (IBAction)login; @end @implementation YYViewController - (IBAction)login {
// 1.提前的表单验证
if (self.username.text.length==) {
[MBProgressHUD showError:@"请输入用户名"];
return;
}
if (self.pwd.text.length==) {
[MBProgressHUD showError:@"请输入密码"];
return;
}
// 2.发送请求给服务器(带上账号和密码)
//添加一个遮罩,禁止用户操作
// [MBProgressHUD showMessage:@"正在努力加载中...."];
// GET请求:请求行\请求头\请求体
//
// 1.设置请求路径
NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
NSURL *url=[NSURL URLWithString:urlStr];
// 2.创建请求对象
NSURLRequest *request=[NSURLRequest requestWithURL:url];
// 3.发送请求
//发送同步请求,在主线程执行
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//(一直在等待服务器返回数据,这行代码会卡住,如果服务器没有返回数据,那么在主线程UI会卡住不能继续执行操作)
NSLog(@"--%d--",data.length);
}
@end
模拟器情况:

打印服务器返回的信息:

//
// YYViewController.m
// 01-NSURLConnection的使用(GET)
//
// Created by apple on 14-6-28.
// Copyright (c) 2014年 itcase. All rights reserved.
// #import "YYViewController.h"
#import "MBProgressHUD+MJ.h" @interface YYViewController ()
@property (weak, nonatomic) IBOutlet UITextField *username;
@property (weak, nonatomic) IBOutlet UITextField *pwd;
- (IBAction)login; @end @implementation YYViewController - (IBAction)login {
// 1.提前的表单验证
if (self.username.text.length==) {
[MBProgressHUD showError:@"请输入用户名"];
return;
}
if (self.pwd.text.length==) {
[MBProgressHUD showError:@"请输入密码"];
return;
}
// 2.发送请求给服务器(带上账号和密码)
//添加一个遮罩,禁止用户操作
[MBProgressHUD showMessage:@"正在努力加载中...."]; //
// 1.设置请求路径
NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
NSURL *url=[NSURL URLWithString:urlStr]; // 2.创建请求对象
NSURLRequest *request=[NSURLRequest requestWithURL:url]; // 3.发送请求
//3.1发送同步请求,在主线程执行
// NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//(一直在等待服务器返回数据,这行代码会卡住,如果服务器没有返回数据,那么在主线程UI会卡住不能继续执行操作) //3.1发送异步请求
//创建一个队列(默认添加到该队列中的任务异步执行)
// NSOperationQueue *queue=[[NSOperationQueue alloc]init];
//获取一个主队列
NSOperationQueue *queue=[NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"--block回调数据--%@---%d", [NSThread currentThread],data.length);
//隐藏HUD,刷新UI的操作一定要放在主线程执行
[MBProgressHUD hideHUD]; //解析data
/*
{"success":"登录成功"}
{"error":"用户名不存在"}
{"error":"密码不正确"}
*/
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@",dict); //判断后,在界面提示登录信息
NSString *error=dict[@"error"];
if (error) {
[MBProgressHUD showError:error];
}else
{
NSString *success=dict[@"success"];
[MBProgressHUD showSuccess:success];
}
}];
NSLog(@"请求发送完毕");
}
@end
模拟器情况(注意这里使用了第三方框架):

打印查看:

NSOperationQueue *queue=[NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//当请求结束的时候调用(有两种结果,一个是成功拿到数据,也可能没有拿到数据,请求失败)
NSLog(@"--block回调数据--%@---%d", [NSThread currentThread],data.length);
//隐藏HUD,刷新UI的操作一定要放在主线程执行
[MBProgressHUD hideHUD]; //解析data
/*
{"success":"登录成功"}
{"error":"用户名不存在"}
{"error":"密码不正确"}
*/
if (data) {//请求成功
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@",dict); //判断后,在界面提示登录信息
NSString *error=dict[@"error"];
if (error) {
[MBProgressHUD showError:error];
}else
{
NSString *success=dict[@"success"];
[MBProgressHUD showSuccess:success];
}
}else //请求失败
{
[MBProgressHUD showError:@"网络繁忙,请稍后重试!"];
} }];
//解析data
/*
{"success":"登录成功"}
{"error":"用户名不存在"}
{"error":"密码不正确"}
*/
要监听服务器返回的data,所以使用<NSURLConnectionDataDelegate>协议
常见大代理方法如下:
#pragma mark- NSURLConnectionDataDelegate代理方法 //当接收到服务器的响应(连通了服务器)时会调用 -(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
使用异步方法发送get请求的代码示例:
//
// YYViewController.m
// 01-NSURLConnection的使用(GET)
//
// Created by apple on 14-6-28.
// Copyright (c) 2014年 itcase. All rights reserved.
// #import "YYViewController.h"
#import "MBProgressHUD+MJ.h" @interface YYViewController ()<NSURLConnectionDataDelegate>
@property (weak, nonatomic) IBOutlet UITextField *username;
@property (weak, nonatomic) IBOutlet UITextField *pwd;
@property(nonatomic,strong)NSMutableData *responseData;
- (IBAction)login; @end @implementation YYViewController - (IBAction)login {
// 1.提前的表单验证
if (self.username.text.length==) {
[MBProgressHUD showError:@"请输入用户名"];
return;
}
if (self.pwd.text.length==) {
[MBProgressHUD showError:@"请输入密码"];
return;
}
// 2.发送请求给服务器(带上账号和密码)
//添加一个遮罩,禁止用户操作
[MBProgressHUD showMessage:@"正在努力加载中...."]; //
// 2.1设置请求路径
NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
NSURL *url=[NSURL URLWithString:urlStr]; // 2.2创建请求对象
// NSURLRequest *request=[NSURLRequest requestWithURL:url];//默认就是GET请求
//设置请求超时
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
request.timeoutInterval=5.0; // 2.3.发送请求
//使用代理发送异步请求(通常应用于文件下载)
NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
[conn start];
NSLog(@"已经发出请求---");
} #pragma mark- NSURLConnectionDataDelegate代理方法
/*
*当接收到服务器的响应(连通了服务器)时会调用
*/
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"接收到服务器的响应");
//初始化数据
self.responseData=[NSMutableData data];
} /*
*当接收到服务器的数据时会调用(可能会被调用多次,每次只传递部分数据)
*/
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"接收到服务器的数据");
//拼接数据
[self.responseData appendData:data];
NSLog(@"%d---%@--",self.responseData.length,[NSThread currentThread]);
} /*
*当服务器的数据加载完毕时就会调用
*/
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"服务器的数据加载完毕");
//隐藏HUD
[MBProgressHUD hideHUD]; //处理服务器返回的所有数据
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil]; //判断后,在界面提示登录信息
NSString *error=dict[@"error"];
if (error) {
[MBProgressHUD showError:error];
}else
{
NSString *success=dict[@"success"];
[MBProgressHUD showSuccess:success];
}
NSLog(@"%d---%@--",self.responseData.length,[NSThread currentThread]);
}
/*
*请求错误(失败)的时候调用(请求超时\断网\没有网\,一般指客户端错误)
*/
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// NSLog(@"请求错误");
//隐藏HUD
[MBProgressHUD hideHUD];
[MBProgressHUD showError:@"网络繁忙,请稍后重试!"];
}
@end
打印查看:

补充:
(1)数据的处理
在didReceiveData:方法中,拼接接收到的所有数据,等所有数据都拿到后,在connectionDidFinishLoading:方法中进行处理
(2)网络延迟
在做网络开发的时候,一定要考虑到网络延迟情况的处理,可以在服务器的代码设置一个断点模拟。
在服务器代码的登录方法中设置断点

设置请求的最大延迟

模拟器情况:

打印查看:

三、NSMutableURLRequest
NSMutableURLRequest是NSURLRequest的子类,常用方法有
设置请求超时等待时间(超过这个时间就算超时,请求失败)- (void)setTimeoutInterval:(NSTimeInterval)seconds;
设置请求方法(比如GET和POST)- (void)setHTTPMethod:(NSString *)method;
设置请求体- (void)setHTTPBody:(NSData *)data;
设置请求头- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
iOS开发网络篇—NSURLConnection基本使用的更多相关文章
- iOS开发网络篇--NSURLConnection
S简介 NSURLConnection: 作用: 1.负责发送请求,建立客户端和服务器的连接发送数据给服务器 2.并收集来自服务器的响应数据 步骤: 1.创建一个NSURL对象,设置请求路径 2.传入 ...
- iOS开发网络篇—NSURLConnection基本使用(一)
一.NSURLConnection的常用类 (1)NSURL:请求地址 (2)NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个NSURL对象,请求方法.请求头.请求体.. ...
- iOS开发网络篇—NSURLConnection基本使用(二)
1.常用的类 NSURL:请求地址 NSURLRequest:一个NSURLRequest对象就代表一个请求,它包含的信息有: 一个NSURL对象 请求方法.请求头.请 ...
- swift开发网络篇—NSURLConnection基本使用
iOS开发网络篇—NSURLConnection基本使用 一.NSURLConnection的常用类 (1)NSURL:请求地址 (2)NSURLRequest:封装一个请求,保存发给服务器的全部数据 ...
- iOS开发网络篇—数据缓存
iOS开发网络篇—数据缓存 一.关于同一个URL的多次请求 有时候,对同一个URL请求多次,返回的数据可能都是一样的,比如服务器上的某张图片,无论下载多少次,返回的数据都是一样的. 上面的情况会造 ...
- iOS开发网络篇—大文件的多线程断点下载
http://www.cnblogs.com/wendingding/p/3947550.html iOS开发网络篇—多线程断点下载 说明:本文介绍多线程断点下载.项目中使用了苹果自带的类,实现了同时 ...
- iOS开发网络篇—HTTP协议
iOS开发网络篇—HTTP协议 说明:apache tomcat服务器必须占用8080端口 一.URL 1.基本介绍 URL的全称是Uniform Resource Locator(统一资源定位符) ...
- iOS开发网络篇—文件的上传
iOS开发网络篇—文件的上传 说明:文件上传使用的时POST请求,通常把要上传的数据保存在请求体中.本文介绍如何不借助第三方框架实现iOS开发中得文件上传. 由于过程较为复杂,因此本文只贴出部分关键代 ...
- iOS开发网络篇—发送json数据给服务器以及多值参数
iOS开发网络篇—发送json数据给服务器以及多值参数 一.发送JSON数据给服务器 发送JSON数据给服务器的步骤: (1)一定要使用POST请求 (2)设置请求头 (3)设置JSON数据为请求体 ...
随机推荐
- .net mvc onexception capture; redirectresult;
need to set filtercontext.result=new redirectresult('linkcustompage'); done. so... ASP.NET MVC异常处理模块 ...
- MVC 4 异步编程简化了
MVC 3 异步编程好麻烦,需要使用异步控制器,一个Action需要拆成两个,很不方便.MVC3的好处是,只需要.NET Framework 4.0就能运行 MVC 4 之后只需要使用async和aw ...
- 网站中集成jquery.imgareaselect实现图片的本地预览和选择截取
imgAreaSelect 是由 Michal Wojciechowski开发的一款非常好用的jquery插件,实现了图片的截取功能.其文档和Demo也是很详尽的.大家可以到http://odynie ...
- ADO.NET 新特性之SqlBulkCopy
在.Net1.1中无论是对于批量插入整个DataTable中的所有数据到数据库中,还是进行不同数据源之间的迁移,都不是很方便.而 在.Net2.0中,SQLClient命名空间下增加了几个新类帮助我们 ...
- AjaxFormSubmit使用demo
官网:http://jquery.malsup.com/form/#download 下载地址 $("#form1").ajaxSubmit({ success: function ...
- CSS 笔记一(Selectors/ Backgrounds/ Borders/ Margins/ Padding/ Height and Width)
Selectors/ Backgrounds/ Borders/ Margins/ Padding/ Height and Width CSS Introduction: CSS stands for ...
- Black World
- java 将list 按长度分割
public static <T> List<List<T>> splitList(List<T> list, int pageSize) { ...
- 模块(序列化(json&pickle)+XML+requests)
一.序列化模块 Python中用于序列化的两个模块: json 跨平台跨语言的数据传输格式,用于[字符串]和 [python基本数据类型] 间进行转换 pickle python内置的数据 ...
- 使用异步js解决模态窗口切换的办法
核心代码 js ="setTimeout(function(){document.getElementsByTagName('Button')[3].click()},100);" ...