您的位置:首页 > 理论基础 > 计算机网络

iOS请求网络数据的方式

2015-08-17 19:57 633 查看
GET同步请求

NSString *strURL = @"http://api.map.baidu.com/place/v2/search?query=银行®ion=大连&output=json&ak=6E823f587c95f0148c19993539b99295";


// 一个正常的URL地址是不允许有中文的,只能有数字和26个英文字母的大小写,和一些特殊的符号避暑&,%等,如果遇到带中文的URL,首先把它进行编码


NSString *strEncode = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",strEncode);


// 接下来,URL符合要求后,就开始进行网络请求,一共分三步
// 1. 根据已经编码好的URL,创建一个NSURL


NSURL *url = [NSURL URLWithString:strEncode];


// 2. 发送一个请求


NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];


// 3. 返回我们要的数据一个NSData对象
// 第一个参数: 刚刚创建的秦秋
// 第二个参数: 返回的一个相应
// 第三个参数: 错误信息


NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];


// 对返回回来的数据,data进行json解析
// 把所有的银行名都打印出来


NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
for (NSMutableDictionary *bankName in dic[@"results"]) {
NSLog(@"%@",bankName[@"address"]);
}

}


POST

NSString *strURL = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];


// 接下来就是POST请求独有的部分
// 把请求方式首先设置成POST请求,默认是GET


[request setHTTPMethod:@"POST"];


// 接下来需要吧请求内容放到request的body中


NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";


// 需要把请求部分的字符串编程NSData类型的对象


NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];


// 把bodydata放到request中


[request setHTTPBody:bodyData];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];


// json解析


NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dic);
for (NSMutableDictionary *newDic in dic[@"news"]) {
NSLog(@"%@",newDic[@"cname"]);
}


GET异步请求

NSString *strURL = @"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];


// 前两步和之前还是一模一样,第三部出现变化, 通过代理的方式进行异步操作


[NSURLConnection connectionWithRequest:request delegate:self];

}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
// 只要接受到服务器放回的相应信息,就会走这个方法,我们在这个方法里需要对接收数据的容器data进行初始化的设置
self.data = [NSMutableData data];

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// 只要返回数据,就会走这个协议方法
// append是累加的意思
[self.data appendData:data];

}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
// 到这,整个请求已经结束,需要把返回的data对imageView的image进行赋值
self.imageView.image = [UIImage imageWithData:self.data];

}


warning 同步和异步的GET请求在步骤上完全相同,只是在第三步使用的是sendSyn的方法,异步使用的是代理的方法,异步是基于同步进行操作

(IBAction)asynPOST:(id)sender {

POST异步

NSString *strURL = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";


// 1. 创建一个url


NSURL *url = [NSURL URLWithString:strURL];


// 2.


NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];


// 3. 设置request请求方式


[request setHTTPMethod:@"POST"];


// 4. 设置body


NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";


// 5. bodyStr - > NSData


NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];


// 6.把body添加到request中


[request setHTTPBody:bodyData];


// 7. 网络请求在子线程里进行请求,请求下来的数据需要通过空间作为载体显示出来,需要把数据在主线程里显示,第二个参数就是指定把数据返回到哪个线程


[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 参数的data就是我们请求下来的数据,接下来数据的解析就再block中进行操作
NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dic[@"new"]);

}];
}


 GET异步通过block的方式
NSString *str = @"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";
//1. 创建一个URL
NSURL *url = [NSURL URLWithString:str];
// 2. 发送一个请求NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 3. 异步
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 数据处理依旧是在block中进行
self.imageView.image = [UIImage imageWithData:data];

}];


warning 总结一下网络请求的步骤: 1.根据网址的字符串,创建NSURL对象; 2. 根据这个url对象,创建一个请求; 3.发送请求,然后获取请求对象,同步和异步的区别就是在请求方法选用有差别,其他都一样

warning POST就是比GET多请求一个,需要给request添加一个body

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 网络 数据