ViewController.m#
//
// ViewController.m
// NetWorking
//
#import "ViewController.h"
#import "NewsModel.h"
#define BASE_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
#define URL_PORT1 @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
#define URL_PORT2 @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
@interface ViewController ()<NSURLConnectionDataDelegate>
@property(nonatomic, strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSMutableData *tempData;//NSURLConnectionDataDelegate
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*
1、同步请求可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作,
2、异步请求不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然可以对UI进行操作,程序可以继续运行
3、GET请求,将参数直接写在访问路径上。操作简单,不过容易被外界看到,安全性不高,地址最多255字节;
4、POST请求,将参数放到body里面。POST请求操作相对复杂,需要将参数和地址分开,不过安全性高,参数放在body里面,不易被捕获。
*/
//1.发送请求
//url : = 网络协议(http://今后可能是https) + 文件路径? + 参数1 & 参数2 ....
//2.接受响应
//3.创建链接对象传输数据
//xcode7之后若想要使用HTTP需要修改info.plist文件
// NSAppTransportSecurity NSDictionary
//
// NSAllowsArbitraryLoads BOOL YES
}
#pragma mark------GET同步 POST同步 -----------------------------------------------
//1.
- (IBAction)GETaction1:(UIButton *)sender {
NSLog(@"GET 同步");
//1.创建URL对象(URL:(网址)统一资源定位符,额被称为网页地址,是因特网上标准的资源的地址)
NSURL *url = [NSURL URLWithString:BASE_URL];
//2.创建链接对象(request:请求,需要)
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//2.1 创建请求方式(默认是get,这一步可以不写)
[request setHTTPMethod:@"get"];
//3.创建响应对象
NSURLResponse *response = nil;
//
NSError *error = nil;
//4.创建连接对象(同步)
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse: &response error: &error];
if (nil !=data) {
//解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
self.dataArray = [NSMutableArray arrayWithCapacity:5];//开辟空间!!!!!!!!!!!!!!!
for (NSDictionary *dic1 in dic[@"news"]) {
NewsModel *newsModel = [NewsModel new];
[newsModel setValuesForKeysWithDictionary:dic1];
[_dataArray addObject:newsModel];
}
//数组检测
for (NewsModel *newmodel in _dataArray) {
NSLog(@"%@",newmodel);
}
// NSLog(@"%@",_dataArray);//此方法打出乱码,因为没遍历;用上边方法
}
}
- (IBAction)POSTaction1:(UIButton *)sender {
NSLog(@"POST 同步");
//1.创建URL对象
NSURL *url = [NSURL URLWithString:URL_PORT1];
//2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//2.1 创建请求方式(必须写)
[request setHTTPMethod:@"post"];//默认请求方式是get
//3.设置请求参数
NSData *tempData = [URL_PORT2 dataUsingEncoding:NSUTF8StringEncoding ];
[request setHTTPBody:tempData];
//4.创建响应对象
NSURLResponse *response = nil;
NSError *error = nil;
//5.创建连接对象
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//6.
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
// NSLog(@"%@",dic);
self.dataArray = [NSMutableArray arrayWithCapacity:5];
for (NSDictionary *dic2 in dic[@"news"]) {
NewsModel *newsmodel2 = [NewsModel new];
[newsmodel2 setValuesForKeysWithDictionary:dic2];
[_dataArray addObject:newsmodel2];
}
for (NewsModel *newamodel2 in _dataArray) {
NSLog( @"%@",newamodel2);
}
}
#pragma mark----- GET异步--BLOCK POST异步__BLOCK --------------------------------------------
//GET异步----------
- (IBAction)GETaction2:(UIButton *)sender {
NSLog(@"GET异步");
//1.创建URl对象
NSURL *url = [NSURL URLWithString:BASE_URL];
//2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//3.直接创建连接对象([NSOperationQueue mainQueue]主队列,多线程内容)
__weak typeof (self)temp = self;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
temp.dataArray = [NSMutableArray arrayWithCapacity:5];
for (NSDictionary *dic2 in dic[@"news"]) {
NewsModel *newsmodel2 = [NewsModel new];
[newsmodel2 setValuesForKeysWithDictionary:dic2];
[_dataArray addObject:newsmodel2];
}
}];
for (NewsModel *newamodel2 in _dataArray) {
NSLog( @"%@",newamodel2);
}
NSLog(@"------------------- ");
}
//POST异步------------
- (IBAction)POSTaction2:(UIButton *)sender {
NSLog(@"POST异步");
//1.创建URL对象
NSURL *url = [NSURL URLWithString:URL_PORT1];
//2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//2.1 创建请求方式(必须写)
[request setHTTPMethod:@"post"];//默认请求方式是get
//3.设置请求参数
NSData *tempData = [URL_PORT2 dataUsingEncoding:NSUTF8StringEncoding ];
[request setHTTPBody:tempData];
//3.直接创建连接对象
__weak typeof (self)temp = self;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
temp.dataArray =[NSMutableArray arrayWithCapacity:5];
for (NSDictionary *dic2 in dic[@"news"]) {
NewsModel *newsmodel2 = [NewsModel new];
[newsmodel2 setValuesForKeysWithDictionary:dic2];
[_dataArray addObject:newsmodel2];
}
}];
for (NewsModel *newamodel2 in _dataArray) {
NSLog( @"%@",newamodel2);
}
}
- (IBAction)GETactiondaili:(UIButton *)sender {
NSLog(@"GET 异步代理");
//1.创建URl对象
NSURL *url = [NSURL URLWithString:BASE_URL];
//2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//创建连接对象,并实现代理
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
//
[connection start];
}
- (IBAction)POSTactiondaili:(UIButton *)sender {
NSLog(@"POST 异步代理");
//1.创建URl对象
NSURL *url = [NSURL URLWithString:URL_PORT1];
//2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"post"];//默认请求方式是get
NSData *tempData = [URL_PORT2 dataUsingEncoding:NSUTF8StringEncoding ];
[request setHTTPBody:tempData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
#pragma mark -----NSURLConnectionDataDelegate-------
//接收到服务器的响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//准备数据接收
self.tempData = [NSMutableData data];
}
//接收到请求的数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//将每次新接收到的数据拼接到原有数据包的后面
[_tempData appendData:data];
}
//加载完毕,开始解析
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:_tempData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
//
// for (NSDictionary *dict in dic[@"news"]) {
// NewsModel *new = [NewsModel new];
// [new setValuesForKeysWithDictionary:dict];
// [_dataArray addObject:new];
// }
//
// for (NewsModel *new in _dataArray) {
// NSLog(@"%@",new.title);
// }
self.dataArray = [NSMutableArray arrayWithCapacity:5];//开辟空间!!!!!!!!!!!!!!!
for (NSDictionary *dic1 in dic[@"news"]) {
NewsModel *newsModel = [NewsModel new];
[newsModel setValuesForKeysWithDictionary:dic1];
[_dataArray addObject:newsModel];
}
//数组检测
for (NewsModel *newmodel in _dataArray) {
NSLog(@"%@",newmodel);
}
}
//打印失败信息
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"文件连接出现error:%@",error);
}
#pragma mark==========================--- 解析新方法 ---========================
- (IBAction)sessionGET:(UIButton *)sender {
NSLog(@"seeeion---GET");
//1.创建URl对象
NSURL *url = [NSURL URLWithString:BASE_URL];
//2.创建session对象
NSURLSession *session = [NSURLSession sharedSession];
//3.创建task(该方法内部做了处理,默认使用get,直接传递URL即可)
NSURLSessionTask *task = [session dataTaskWithRequest:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//数据操作
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
self.dataArray = [NSMutableArray arrayWithCapacity:5];//开辟空间!!!!!!!!!!!!!!!
for (NSDictionary *dic1 in dic[@"news"]) {
NewsModel *newsModel = [NewsModel new];
[newsModel setValuesForKeysWithDictionary:dic1];
[_dataArray addObject:newsModel];
}
//数组检测
for (NewsModel *newmodel in _dataArray) {
NSLog(@"%@",newmodel);
}
}];
//4.起动会话
[task resume];
}
- (IBAction)sessionPOST:(UIButton *)sender {
NSLog(@"seeeion---POST");
//1.创建URL对象
NSURL *url = [NSURL URLWithString:BASE_URL];
//2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//创建请求方式
[request setHTTPBody:@"post"];
NSData *tempData = [URL_PORT2 dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:tempData];
//3.建立对话
NSURLSession *session = [NSURLSession sharedSession];
//session支持3种类型的任务:
//1. NSURLSessionDataTask(加载数据)
//2. NSURLSessionDownloadTask(下载)
//3. NSURLSessionUploadTask(上传)
NSLog(@"---%d",[[NSThread currentThread] isMainThread]);//关于多线程
__weak typeof (self)temp = self;
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//解析
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);
NSLog(@"----------------------%d",[[NSThread currentThread] isMainThread]);
//回到主线程(刷新数据)
dispatch_async(dispatch_get_main_queue(), ^{
// [temp.tableView reloadData];
});
}];
//4. 启动任务
[task resume];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
//
// NewsModel.h
// NetWorking
//
//
#import <Foundation/Foundation.h>
@interface NewsModel : NSObject
@property (nonatomic, assign)NSInteger code;
@property (nonatomic, strong)NSString *cid;
@property (nonatomic, strong)NSString *cname;
@property (nonatomic, assign)NSInteger commentCount;
@property (nonatomic, strong)NSString *ID;
@property (nonatomic, strong)NSString *lastUpdateTime;
@property (nonatomic, strong)NSString *nswaUrl;
@property (nonatomic, strong)NSString *picUrl;
@property (nonatomic, assign)NSInteger rownum;
@property (nonatomic, strong)NSString *sequence;
@property (nonatomic, strong)NSString *summary;
@property (nonatomic, strong)NSString *title;
@property (nonatomic, strong)NSString *type;
@property (nonatomic, strong)NSString *typeld;
@end
NewsModel.m#
//
// NewsModel.m
// NetWorking
//
#import "NewsModel.h"
@implementation NewsModel
//容错处理
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
if ([key isEqualToString:@"id"]) {
_ID = value;
}
}
- (NSString *)description
{
return [NSString stringWithFormat:@"%@", _title];
}
@end
网友评论