网络请求判断连接和状态码
2016-05-27 13:52
344 查看
NSURL *url = [NSURL
URLWithString:@"http://news.coolban.com";
[NSURLConnection
sendAsynchronousRequest:request
queue:[NSOperationQueue
mainQueue]
completionHandler:^(NSURLResponse *
_Nullable response,
NSData *
_Nullable data,
NSError *
_Nullable connectionError) {
//连接错误
if(connectionError){
errorBlock();
// NSLog(@"%@",connectionError);
return;
}
//得到状态码
//判断状态码是200或者304就是成功
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode ==
200 || httpResponse.statusCode ==
304){
//访问成功
//json反序列化
id result = [NSJSONSerialization
JSONObjectWithData:data
options:0 error:NULL];
NSMutableArray *mArray = [NSMutableArray
array];
//遍历array
[result enumerateObjectsUsingBlock:^(id
_Nonnull obj, NSUInteger idx,
BOOL * _Nonnull stop) {
CZNews *news = [CZNews
newsWithDictionary:obj];
[mArray addObject:news];
}];
sucessBlock(mArray.copy);
}else{
errorBlock();
// NSLog(@"服务器错误");
}
}];
URLWithString:@"http://news.coolban.com";
[NSURLConnection
sendAsynchronousRequest:request
queue:[NSOperationQueue
mainQueue]
completionHandler:^(NSURLResponse *
_Nullable response,
NSData *
_Nullable data,
NSError *
_Nullable connectionError) {
//连接错误
if(connectionError){
errorBlock();
// NSLog(@"%@",connectionError);
return;
}
//得到状态码
//判断状态码是200或者304就是成功
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode ==
200 || httpResponse.statusCode ==
304){
//访问成功
//json反序列化
id result = [NSJSONSerialization
JSONObjectWithData:data
options:0 error:NULL];
NSMutableArray *mArray = [NSMutableArray
array];
//遍历array
[result enumerateObjectsUsingBlock:^(id
_Nonnull obj, NSUInteger idx,
BOOL * _Nonnull stop) {
CZNews *news = [CZNews
newsWithDictionary:obj];
[mArray addObject:news];
}];
sucessBlock(mArray.copy);
}else{
errorBlock();
// NSLog(@"服务器错误");
}
}];
相关文章推荐
- HTTP 协议简介
- 【UVALive - 3487】 Duopoly(网络流-最小割)
- 网络地址-InetAddress类
- THE ONE使用笔记(3)——DirectDelivery源码分析
- THE ONE使用笔记(2)——路由算法顽健性分析
- Linux C编程章节五:网络编程
- GSM Hacking:如何对GSM/GPRS网络测试进行测试
- 配置tomcat的https通信(单向认证)
- okhttp框架的使用
- Xcode 7中http通信出现如下错误
- HttpURLConnection和Httpclient get请求
- HTTP协议及报文分析
- Burpsuite之Http Basic认证爆破
- TCP/IP简介
- 复用TCP连接提升流媒体服务器之间流量转发效率
- 异步请求网络
- Oracle 11G Client 客户端配制客户端监听和网络服务名
- iOS网络编程开发—JSON解析与XML解析
- angularjs2 学习笔记(五) http服务
- Python即时网络爬虫项目: 内容提取器的定义